﻿Imports System.ComponentModel
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms.VisualStyles
Imports System.Runtime.InteropServices
Imports FixSoft.Tools.Common
Imports System.Drawing.Design

''' <summary>
''' Fix soft HyperAero Form is an Aero Form.It supports Gradients,Animations,Sounds,Power Tools,Array Tools and more.
''' Works on both xp and Win7.Aero feature will be disabled in Win Xp.
''' Fix soft Blog: www.fixosoft.wordpress.com
''' </summary>
Public Class HyperAero
    Private BackgorundGradientv As GradientBlend = New GradientBlend(New Color() {Color.AliceBlue, Color.RoyalBlue, Color.Navy}, New Single() {0, 0.5, 1})
    ''' <summary>
    ''' The ColorBlend used to fill the form.
    ''' </summary>
    <Description("The ColorBlend used to fill the form"), _
    Category("Appearance"), _
    Editor(GetType(BlendTypeEditor), GetType(UITypeEditor))> _
    Public Property BackgroundGradient() As GradientBlend
        Get
            Return BackgorundGradientv
        End Get
        Set(ByVal value As GradientBlend)
            BackgorundGradientv = value
            Me.Invalidate()
        End Set
    End Property
    Sub ReadyForAero()
        If AeroEnabled = False Then
            Exit Sub
        End If
        If AutoOffGradientOnAero Then
            Me.isgv = False
        End If
        Me.BackgroundImage = Nothing
        Me.BackColor = Color.Black
    End Sub
    Dim TempGE As Boolean
#Region "AeroForm"
#Region "Blur"
    ''' <summary>
    ''' Set Aero Blur for background of Form with special Control (That recommand it be a Panel).
    ''' </summary>
    ''' <param name="Control">A Control that recommand it be a panel for set Aero Blur to its region.</param>
    Public Sub SetAeroBlur(ByVal Control As Control)
        Dim Temp As New BlurBehind(Handle)
        Temp.Enabled = True
        Using TControl As Control = CommonTools.GetActualLocationAsControl(Control)
            Temp.RectRegion = New AeroAPIs.RECT(TControl.Left, TControl.Top, TControl.Right, TControl.Bottom)
        End Using
        Temp = Nothing
    End Sub
    ''' <summary>
    ''' Set Aero Blur for background of Form.
    ''' </summary>
    Public Sub SetAeroBlur()
        Dim Temp As New BlurBehind(Me.Handle)
        Temp.Enabled = True
        Temp = Nothing
    End Sub
#End Region
#Region "AutoChanges"
    Dim RealBackGroundImage As Image
    ''' <summary>
    ''' Gets or sets Is Automatical change AeroBackgound to True when Aero is Enable?
    ''' </summary>
    <Description("Is Automatical change AeroBackgound to True when Aero is Enable?"), Category("Aero"), DefaultValue(True)>
    Public Property AutoAeroChange As Boolean = True
    Dim ACt As Color = AeroColor
    Dim ATt As Boolean = AeroTransparentyEnabled

    Private Sub HyperAero_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated, Me.Deactivate
        Invalidate()
    End Sub
    Private Sub HyperAero_AeroColorOrTransparentyChanged(ByVal Sender As Object, ByVal e As EventArgs) Handles Me.AeroColorOrTransparentyChanged
        If AeroColor <> ACt Then
            ACt = AeroColor
            RaiseEvent AeroColorChanged(Me, EventArgs.Empty)
        End If
        If AeroTransparentyEnabled <> ATt Then
            ATt = AeroTransparentyEnabled
            RaiseEvent AeroTransparentyChanged(Me, EventArgs.Empty)
        End If
    End Sub
    Private Sub FrmHyperGrahic_AeroEffectDisabled(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.AeroEffectDisabled
        If DesignMode Then
            Exit Sub
        End If
        If AutoAeroChange Then
            Me.BackgroundImage = RealBackGroundImage
            GradientEnabled = TempGE
            Me.BackColor = SystemColors.Control
        End If
    End Sub
    Private Sub FrmHyperGrahic_AeroEffectEnabled(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.AeroEffectEnabled
        If DesignMode Then
            Exit Sub
        End If
        If AutoAeroChange Then
            TempGE = GradientEnabled
            ResetAeroBackground()
        End If
    End Sub
    ''' <summary>
    ''' Gets or sets does drag automatically extended area to Windows Aero on the Form?
    ''' </summary>
    <Description("Does drag automatically extended area to Windows Aero on the Form?"), Category("Aero"), DefaultValue(True)>
    Public Property DragAeroArea As Boolean = True
    ''' <summary>
    ''' Gets or sets does move and drag Form automatically when user drag it?
    ''' </summary>
    <Description("Does move and drag Form automatically when user drag it?"), Category("Behavior"), DefaultValue(False)>
    Public Property DragForm As Boolean = False

    Private Declare Function ReleaseCapture Lib "user32" () As Integer


    Private Const HTCAPTION As Short = 2
    Private Const WM_NCLBUTTONDOWN As Short = &HA1S

    Private Const WM_SYSCOMMAND As Short = &H112S
    ''' <summary>
    ''' Occurs when DragMove methode called.
    ''' </summary>
    <Description("Occurs when DragMove methode called."), Category("Behavior")>
    Public Event Draging(ByVal Sender As Object, ByVal e As CancelEventArgs)
    ''' <summary>
    ''' Drag the Form with Aero Shake support (Like DragMove in WPF).
    ''' </summary>
    Public Sub DragMove()
        Dim ce As New CancelEventArgs
        RaiseEvent Draging(Me, ce)
        If ce.Cancel = True Then
            Exit Sub
        End If
        ReleaseCapture()
        AeroAPIs.SendMessage(Handle.ToInt32, WM_NCLBUTTONDOWN, HTCAPTION, 0)
    End Sub
    ''' <summary>
    ''' Raise event PaintNonClientArea.
    ''' </summary>
    ''' <param name="e">Paint argument that has graphics object.</param>
    Protected Overridable Sub OnPaintNonClientArea(ByVal e As PaintEventArgs)
        RaiseEvent PaintNonClientArea(Me, e)
    End Sub
    ''' <summary>
    ''' Redraw non client area of form.
    ''' </summary>
    Public Sub InvalidateNonClientArea()
        If IsDisposed Then
            Exit Sub
        End If
        Dim g As Graphics = Graphics.FromHdc(New IntPtr(AeroAPIs.GetWindowDC(Handle.ToInt32)))
        OnPaintNonClientArea(New PaintEventArgs(g, New Rectangle(New Point(g.ClipBounds.Location.X, g.ClipBounds.Location.Y), g.ClipBounds.Size.ToSize)))
    End Sub
    '<DebuggerStepThrough()>
    Protected Overrides Sub WndProc(ByRef e As Message)
        If e.Msg = AeroAPIs.WM_NCACTIVATE Then
            If CaptionBarRenderMode = CaptionBarStates.Active AndAlso e.WParam = False Then
                e.WParam = True
            End If
        End If
        MyBase.WndProc(e)
        If e.Msg = AeroAPIs.WM_SYNCPAINT OrElse e.Msg = AeroAPIs.WM_NCCREATE OrElse e.Msg = AeroAPIs.WM_NCPAINT OrElse e.Msg = AeroAPIs.WM_PAINT Then
            InvalidateNonClientArea()
        End If
        If AeroEnabled AndAlso DragAeroArea Then
            If e.Msg = &H84 AndAlso e.Result = &H1 Then
                Dim clientPoint = Me.PointToClient(New Point(MousePosition.X, MousePosition.Y))
                If IsOutsideMargins(clientPoint, ClientSize) = False Then
                    e.Result = &H2
                End If
            End If
        End If
    End Sub
    Private AMLeft As Integer = -1
    Private AMRight As Integer = -1
    Private AMTop As Integer = -1
    Private AMBottom As Integer = -1
    ''' <summary>
    ''' Gets or sets Aero margins (for using in draging Aero area.).
    ''' </summary>
    <Browsable(False), Category("Aero")>
    Public Property AeroMargins As AeroAPIs.MARGINS
        Get
            Dim Temp As New AeroAPIs.MARGINS
            Temp.Left = AMLeft
            Temp.Right = AMRight
            Temp.Top = AMTop
            Temp.Bottom = AMBottom
            Return Temp
        End Get
        Set(ByVal value As AeroAPIs.MARGINS)
            AMLeft = value.Left
            AMRight = value.Right
            AMTop = value.Top
            AMBottom = value.Bottom
        End Set
    End Property


    ''' <summary>
    ''' Returns whether a point in client coordinates is outside the margins defined by this instance.
    ''' </summary>
    ''' <param name="clientPoint">Point in client coordinates.</param>
    Friend Function IsOutsideMargins(ByVal clientPoint As Point, ByVal clientSize As Size) As Boolean
        If AeroEnabled = False Then
            Return True
        End If
        If ExceptAeroEnabled = False Then
            Return False
        End If
        Return Not (clientPoint.X < AMLeft OrElse clientPoint.X > (clientSize.Width - AMRight) OrElse clientPoint.Y < AMTop OrElse clientPoint.Y > (clientSize.Height - AMBottom))
    End Function

#End Region
#Region "Properties"
    ''' <summary>
    ''' Gets or sets Is automatically change GradientEnabled to False if Aero enabled?
    ''' </summary>
    <Description("Is automatically change GradientEnabled to False if Aero enabled?"), Category("Aero"), DefaultValue(True)>
    Public Property AutoOffGradientOnAero As Boolean = True
    ''' <summary>
    ''' Gets or sets Is Windows Aero Enabled?
    ''' </summary>
    <Description("Is Windows Aero Enabled?"), Category("Aero"), DefaultValue(True), Browsable(False)>
    Public Property AeroEnabled As Boolean
        Get
            If AeroBackgroundEnabled = False AndAlso DesignMode = False Then
                Return False
            End If
            If AeroSupport Then
                Dim Enabled As Boolean
                AeroAPIs.DwmIsCompositionEnabled(Enabled)
                Return Enabled
            Else
                Return False
            End If

        End Get
        Set(ByVal value As Boolean)
            If DesignMode Then
                Exit Property
            End If
            Try
                AeroAPIs.DwmEnableComposition(value)
            Catch ex As Exception

            End Try
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets Is Windows Aero Enabled?
    ''' </summary>
    <Description("Is Windows Aero Enabled?"), Category("Aero"), DefaultValue(True), Browsable(False)>
    Public Shared Property WindowsAeroEnabled As Boolean
        Get
            If AeroSupport Then
                Dim Enabled As Boolean
                AeroAPIs.DwmIsCompositionEnabled(Enabled)
                Return Enabled
            Else
                Return False
            End If

        End Get
        Set(ByVal value As Boolean)
            Try
                AeroAPIs.DwmEnableComposition(value)
            Catch ex As Exception

            End Try
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets Labels Glow Value.
    ''' </summary>
    <Description("Sets Labels Glow Value."), Category("Aero"), DefaultValue(9)>
    Public Property GlowValue As Integer = 9
    ''' <summary>
    ''' Gets or sets Is Automatical call ShowLabel for Labels?
    ''' It can be slow in big forms.
    ''' </summary>
    <Description("Is Automatical call ShowLabel for Labels?" + vbNewLine + "It can be slow in big forms."), Category("Aero"), DefaultValue(True)>
    Public Property AutoShowLabels As Boolean = True
    ''' <summary>
    ''' Gets or sets current Aero Color.
    ''' </summary>
    <Description("Current Aero Color."), Category("Aero")>
    Public Shared Property AeroColor As Color
        Get
            If AeroSupport = False Then
                Return Color.Transparent
            End If
            Dim AARRGGBB = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM", "ColorizationColor", "00000000")
            Dim Argb As Integer = Convert.ToInt32(CLng(AARRGGBB.ToString), 10)
            Return System.Drawing.Color.FromArgb(Argb)
        End Get
        Set(ByVal value As Color)
            If AeroSupport = False Then
                Exit Property
            End If
            Dim Color(3) As Byte
            Color(0) = value.B
            Color(1) = value.G
            Color(2) = value.R
            Color(3) = value.A
            Dim p As AeroAPIs.WDM_COLORIZATION_PARAMS
            AeroAPIs.DwmGetColorizationParameters(p)
            If IntensityForAeroColor <> -1 Then
                p.Intensity = IntensityForAeroColor
            End If
            p.Color1 = BitConverter.ToUInt32(Color, 0)
            AeroAPIs.DwmSetColorizationParameters(p, True)
            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM", "ColorizationColor", value.ToArgb, Microsoft.Win32.RegistryValueKind.DWord)
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets intensity of Aero Color.
    ''' It uses in next Aero Color change (not now).
    ''' Use -1 to use current value of Windows.
    ''' </summary> 
    Public Shared Property IntensityForAeroColor As Integer = 50
    ''' <summary>
    ''' Gets or sets Aero Transparenty Enabled.
    ''' If you changed this property,You need to wait for a restart to changes applied.If you don't like waiting,you most change AeroEnabled to False and then change AeroEnabled to True.
    ''' </summary>
    <Browsable(False), Description("Aero Transparenty Enabled."), Category("Aero"), DefaultValue(True)>
    Public Property AeroTransparentyEnabled As Boolean
        Get
            If AeroSupport = False Then
                Return False
            End If
            Dim TransparentyEnable = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM", "ColorizationOpaqueBlend", "00000001")
            Dim TransparentyEnabled As Boolean
            If TransparentyEnable = 0 Then
                TransparentyEnabled = True
            Else
                TransparentyEnabled = False
            End If
            Return TransparentyEnabled
        End Get
        Set(ByVal value As Boolean)
            If AeroSupport = False Then
                Exit Property
            End If
            Dim p As AeroAPIs.WDM_COLORIZATION_PARAMS
            AeroAPIs.DwmGetColorizationParameters(p)
            p.Opaque = Not value
            AeroAPIs.DwmSetColorizationParameters(p, True)
            Dim AeroValue As String
            If value Then
                AeroValue = "00000000"
            Else
                AeroValue = "00000001"
            End If
            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM", "ColorizationOpaqueBlend", AeroValue, Microsoft.Win32.RegistryValueKind.DWord)
        End Set
    End Property
#End Region
#Region "AeroEvents"
    ''' <summary>
    ''' Occurs when the control's non client area is redrawn.
    ''' </summary>
    ''' <remarks>Control's client area is redrawn,too.</remarks>
    Public Event PaintNonClientArea As PaintEventHandler
    ''' <summary>
    ''' Occurs when Areo Turn on.
    ''' </summary>
    <Description("Occurs when Areo Turn on."), Category("Aero")>
    Public Event AeroEffectEnabled(ByVal sender As Object, ByVal e As EventArgs)
    ''' <summary>
    ''' Occurs when Areo Turn off.
    ''' </summary>
    <Description("Occurs when Areo Turn off."), Category("Aero")>
    Public Event AeroEffectDisabled(ByVal sender As Object, ByVal e As EventArgs)
    ''' <summary>
    ''' Occurs when Aero Color or AeroTransparentyEnabled changed.
    ''' </summary>
    ''' <param name="Sender">Gets Sender.</param>
    <Description("Occurs when Aero Color or AeroTransparentyEnabled changed."), Category("Aero")>
    Public Event AeroColorOrTransparentyChanged As EventHandler
    ''' <summary>
    ''' Occurs when AeroTransparentyEnabled changed.
    ''' </summary>
    ''' <param name="Sender">Gets Sender.</param>
    <Description("Occurs when AeroTransparentyEnabled changed."), Category("Aero")>
    Public Event AeroTransparentyChanged As EventHandler
    ''' <summary>
    ''' Occurs when Aero Color changed.
    ''' </summary>
    ''' <param name="Sender">Gets Sender.</param>
    <Description("Occurs when Aero Color changed."), Category("Aero")>
    Public Event AeroColorChanged As EventHandler
    Private WithEvents WindowListener As New HookWindow()

    Private Sub WindowListener_ColorChanged() Handles WindowListener.ColorChanged
        Dim AARRGGBB = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM", "ColorizationColor", "00000000")
        Dim Argb As Integer = Convert.ToInt32(CLng(AARRGGBB.ToString), 10)
        Dim NewColor As Color = System.Drawing.Color.FromArgb(Argb)
        Dim TransparentyEnable = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM", "ColorizationOpaqueBlend", "00000001")
        Dim TransparentyEnabled As Boolean
        If TransparentyEnable = 0 Then
            TransparentyEnabled = True
        Else
            TransparentyEnabled = False
        End If
        RaiseEvent AeroColorOrTransparentyChanged(Me, EventArgs.Empty)
    End Sub
    Private Sub WindowListener_MessageArrived(ByVal sender As Object, ByVal e As System.EventArgs) Handles WindowListener.MessageArrived
        If WindowsAeroEnabled Then
            RaiseEvent AeroEffectEnabled(Me, New EventArgs)
        Else
            RaiseEvent AeroEffectDisabled(Me, New EventArgs)
        End If
    End Sub
    '   <DebuggerStepThrough()>
    Friend Class HookWindow
        Inherits NativeWindow


        Sub New()
            Dim cp As New CreateParams()
            Me.CreateHandle(cp)
        End Sub


        Public Event MessageArrived(ByVal sender As Object, ByVal e As EventArgs)
        Public Event ColorChanged()
        Private Const WM_SYSCOLORCHANGE As Int32 = &H31E '&H15
        Private Const WM_DWMNCRENDERINGCHANGED As Integer = &H31F
        Private Const WM_DWMCOLORIZATIONCOLORCHANGED As Integer = 800
        <DebuggerStepThrough()>
        Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
            If m.Msg = WM_SYSCOLORCHANGE OrElse m.Msg = WM_DWMNCRENDERINGCHANGED Then
                RaiseEvent MessageArrived(Me, New EventArgs)
            End If
            If m.Msg = WM_DWMCOLORIZATIONCOLORCHANGED Then
                RaiseEvent ColorChanged()
            End If
            MyBase.WndProc(m)
        End Sub
        Protected Overrides Sub Finalize()
            Me.DestroyHandle()
            MyBase.Finalize()
        End Sub
    End Class
#End Region
#Region "Subs"
    ''' <summary>
    ''' Call DwmExtendFrameIntoClientArea with nagetive numbers and set backcolor to black.
    ''' </summary>
    Overridable Sub ResetAeroBackground()
        If AeroBackgroundEnabled = False OrElse IsDisposed Then
            Exit Sub
        End If
        ReadyForAero()
        Dim margins As New AeroAPIs.MARGINS
        margins.Left = -1
        margins.Right = -1
        margins.Top = -1
        margins.Bottom = -1
        AMBottom = -1
        AMLeft = -1
        AMRight = -1
        AMTop = -1
        If AeroEnabled Then
            AeroAPIs.DwmExtendFrameIntoClientArea(Handle, margins)
        End If
        ExceptAeroEnabled = False
    End Sub
    ''' <summary>
    ''' Call ResetAeroTransparenty or ExceptAeroTransparenty (BackgroundControl(0)).
    ''' </summary>
    Public Sub SetAeroTransparenty()
        If ExceptAeroEnabled Then
            ExcludeControlFromAero(BackgroundControl(0))
        Else
            ResetAeroBackground()
        End If
    End Sub
    Dim BackgroundControlv As Control() = New Control() {}
    ''' <summary>
    ''' Gets or sets some Controls for Aero Gradient using.
    ''' </summary>
    <Category("Aero"), Description("Some Controls for Aero Gradient using.")>
    Public Property BackgroundControl As Control()
        Get
            Return BackgroundControlv
        End Get
        Set(ByVal value As Control())
            BackgroundControlv = value
            Invalidate()
        End Set
    End Property
    Dim ExceptAeroEnabled As Boolean = False
    ''' <summary>
    ''' Many controls doesn't support Aero Frame.So,this methode exclude a Control from Aero background.
    ''' </summary>
    ''' <param name="Control" >Control that be except.</param>
    ''' <param name="InValue" >A number except area go to in.</param>
    Overridable Sub ExcludeControlFromAero(ByVal Control As Control, Optional ByVal InValue As Integer = 3, Optional ByVal AddToBackgroundControl As Boolean = True)
        If AeroBackgroundEnabled = False OrElse IsDisposed Then
            Exit Sub
        End If
        ReadyForAero()
        Dim ClientScreen As Rectangle = Me.RectangleToScreen(Me.ClientRectangle)
        Dim ControlScreen As Rectangle = Control.RectangleToScreen(Control.ClientRectangle)
        Dim margins As New AeroAPIs.MARGINS
        margins.Left = ControlScreen.Left - ClientScreen.Left + InValue
        margins.Right = ClientScreen.Right - ControlScreen.Right + InValue
        margins.Top = ControlScreen.Top - ClientScreen.Top + InValue
        margins.Bottom = ClientScreen.Bottom - ControlScreen.Bottom + InValue
        AMLeft = margins.Left
        AMRight = margins.Right
        AMTop = margins.Top
        AMBottom = margins.Bottom
        If AeroEnabled Then
            AeroAPIs.DwmExtendFrameIntoClientArea(Handle, margins)
        End If
        If AddToBackgroundControl Then
            Array.Resize(Of Control)(BackgroundControl, BackgroundControl.Length + 1)
            BackgroundControl(BackgroundControl.Length - 1) = Control
        End If
        ExceptAeroEnabled = True
    End Sub
    ''' <summary>
    ''' Many controls doesn't support Aero Frame.So,this methode exclude an area from Aero background.
    ''' </summary>
    Overridable Sub ExcludeFromAero(ByVal Margins As AeroAPIs.MARGINS)
        If AeroEnabled = False OrElse AeroBackgroundEnabled = False OrElse IsDisposed Then
            Exit Sub
        End If
        ReadyForAero()
        AMLeft = Margins.Left
        AMRight = Margins.Right
        AMTop = Margins.Top
        AMBottom = Margins.Bottom
        AeroAPIs.DwmExtendFrameIntoClientArea(Handle, Margins)
        ExceptAeroEnabled = True
    End Sub

    ''' <summary>
    ''' A method to measure the size necessary in which to fit the text.
    ''' </summary>
    ''' <param name="graphics">The Graphics object on which to draw.</param>
    ''' <param name="text">The text to draw.</param>
    ''' <param name="font">The font used to draw text.</param>
    ''' <param name="format">The text format flags to apply.</param>
    ''' <param name="glowSize">The size in pixels of the glow around text.</param>
    ''' <returns>The size needed to draw text with glow.</returns>
    <Security.Permissions.PermissionSet(Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
    Public Shared Function MeasureThemedText(ByVal Graphics As Graphics, ByVal Text As String, ByVal Font As Font, ByVal Size As Size, ByVal format As TextFormatFlags, ByVal GlowSize As Integer) As Size
        Dim sz As Size = Drawing.Size.Empty
        If WindowsAeroEnabled Then
            Dim renderer As New VisualStyleRenderer(VisualStyleElement.TextBox.TextEdit.Normal)

            Dim hTheme As IntPtr = renderer.Handle

            Dim sourceDC As IntPtr = Graphics.GetHdc()

            Dim hFont As IntPtr = Font.ToHfont()
            Dim originalFont As IntPtr = AeroAPIs.SelectObject(sourceDC, hFont)

            Dim rc As AeroAPIs.RECT

            Dim rcIn As New AeroAPIs.RECT(New Rectangle(Point.Empty, Size))

            If AeroAPIs.GetThemeTextExtent(hTheme, sourceDC, 0, 0, Text, -1, _
             CInt(format), rcIn, rc) = AeroAPIs.S_OK Then
                sz = rc.ToRectangle().Size
            End If

            Graphics.ReleaseHdc()

            AeroAPIs.SelectObject(sourceDC, originalFont)
            AeroAPIs.DeleteObject(hFont)

            sz.Width += GlowSize

            sz.Height += GlowSize
        Else
            sz = TextRenderer.MeasureText(Text, Font, Size, format)
        End If

        Return sz
    End Function
    ''' <summary>
    ''' Gets Is current OS Windows Vista or later?
    ''' </summary>
    Public Shared ReadOnly Property AeroSupport As Boolean
        Get
            Return Environment.OSVersion.Version.Major >= 6
        End Get
    End Property

    ''' <summary>
    ''' Get TextFormatFlags of a label.
    ''' </summary>
    ''' <param name="Label" >A Label that its options use to create a TextFormatFlags.</param>
    Public Shared Function GetTextFormatFlags(ByVal Label As Label) As TextFormatFlags
        Return GetTextFormatFlags(Label.TextAlign, Label.RightToLeft, Label.Text, Label.UseMnemonic)
    End Function
    ''' <summary>
    ''' Get TextFormatFlags of a label.
    ''' </summary>
    ''' <param name="TextAlign">TextAlign of label.</param>
    ''' <param name="RightToLeft">RightToLeft of Label.</param>
    ''' <param name="Text">Text of Label.</param>
    Public Shared Function GetTextFormatFlags(ByVal TextAlign As ContentAlignment, Optional ByVal RightToLeft As RightToLeft = Windows.Forms.RightToLeft.No, Optional ByVal Text As String = "", Optional ByVal UseMnemonic As Boolean = False) As TextFormatFlags
        Dim LabelAlign As TextFormatFlags
        Select Case TextAlign
            Case Drawing.ContentAlignment.BottomCenter
                LabelAlign = TextFormatFlags.Bottom Or TextFormatFlags.HorizontalCenter
            Case Drawing.ContentAlignment.BottomLeft
                LabelAlign = TextFormatFlags.Bottom Or TextFormatFlags.Left
            Case Drawing.ContentAlignment.BottomRight
                LabelAlign = TextFormatFlags.Bottom Or TextFormatFlags.Right
            Case Drawing.ContentAlignment.MiddleCenter
                LabelAlign = TextFormatFlags.VerticalCenter Or TextFormatFlags.HorizontalCenter
            Case Drawing.ContentAlignment.MiddleLeft
                LabelAlign = TextFormatFlags.VerticalCenter Or TextFormatFlags.Left
            Case Drawing.ContentAlignment.MiddleRight
                LabelAlign = TextFormatFlags.VerticalCenter Or TextFormatFlags.Right
            Case Drawing.ContentAlignment.TopCenter
                LabelAlign = TextFormatFlags.Top Or TextFormatFlags.HorizontalCenter
            Case Drawing.ContentAlignment.TopLeft
                LabelAlign = TextFormatFlags.Top Or TextFormatFlags.Left
            Case Drawing.ContentAlignment.TopRight
                LabelAlign = TextFormatFlags.Top Or TextFormatFlags.Right
        End Select
        If Text.Contains(vbNewLine) = False Then
            LabelAlign = LabelAlign Or TextFormatFlags.SingleLine
        End If
        If RightToLeft = Windows.Forms.RightToLeft.Yes Then
            LabelAlign = LabelAlign Or TextFormatFlags.RightToLeft
        End If
        If Not UseMnemonic Then
            LabelAlign = LabelAlign Or TextFormatFlags.NoPrefix
        End If
        Return LabelAlign
    End Function
    ''' <summary>
    ''' A method to draw glowing text if the operating system supports it.
    ''' If the os does not support it then standard GDI text is drawn.
    ''' </summary>
    ''' <param name="graphics">The Graphics object on which to draw.</param>
    ''' <param name="text">The text to draw.</param>
    ''' <param name="font">The font used to draw text.</param>
    ''' <param name="bounds">The bounding rectangle within which to draw.</param>
    ''' <param name="ForeColor">The color used to draw the text.</param>
    ''' <param name="format">The text format flags to apply.</param>
    ''' <param name="glowSize">The size in pixels of the glow around text.</param>
    Public Shared Sub DrawGlowText(ByVal Graphics As Graphics, ByVal Text As String, ByVal Font As Font, ByVal bounds As Rectangle, ByVal ForeColor As Color, ByVal Format As TextFormatFlags, ByVal GlowSize As Integer)
        If WindowsAeroEnabled = False Then
            ' Graphics.DrawString(Text, Font, New SolidBrush(ForeColor), bounds.Location)
            TextRenderer.DrawText(Graphics, Text, Font, bounds, ForeColor, Format)
            Exit Sub
        End If
        ' Variables used later.
        Dim SavedBitmap As IntPtr = IntPtr.Zero
        Dim SavedFont As IntPtr = IntPtr.Zero
        Dim MainHDC As IntPtr = Graphics.GetHdc
        Dim MemHDC As IntPtr = AeroAPIs.CreateCompatibleDC(MainHDC)
        Dim BtmInfo As New AeroAPIs.BITMAPINFO
        Dim TextRect As New AeroAPIs.RECT(0, 0, bounds.Right - bounds.Left + 2 * 15, bounds.Bottom - bounds.Top + 2 * 15)
        Dim ScreenRect As New AeroAPIs.RECT(bounds.Left - 15, bounds.Top - 15, bounds.Right + 15, bounds.Bottom + 15)
        Dim hFont As IntPtr = Font.ToHfont

        Try
            Dim Renderer As VisualStyleRenderer = New VisualStyleRenderer(System.Windows.Forms.VisualStyles.VisualStyleElement.Window.Caption.Active)
            ' Memory bitmap to hold the drawn glowed text.
            BtmInfo.bmiHeader.biSize = Marshal.SizeOf(BtmInfo.bmiHeader)

            With BtmInfo
                .bmiHeader.biWidth = bounds.Width + 30
                .bmiHeader.biHeight = -bounds.Height - 30
                .bmiHeader.biPlanes = 1
                .bmiHeader.biBitCount = 32
            End With

            ' Create a DIB Section for this bitmap from the graphics object.
            Dim dibSection As IntPtr = AeroAPIs.CreateDIBSection(MainHDC, BtmInfo, 0, 0, IntPtr.Zero, 0)

            ' Save the current handles temporarily.
            SavedBitmap = AeroAPIs.SelectObject(MemHDC, dibSection)
            SavedFont = AeroAPIs.SelectObject(MemHDC, hFont)

            ' Holds the properties of the text (size and color , ...etc).
            Dim TextOptions As AeroAPIs.S_DTTOPTS = New AeroAPIs.S_DTTOPTS

            With TextOptions
                .dwSize = Marshal.SizeOf(TextOptions)
                .dwFlags = AeroAPIs.DTT_COMPOSITED Or AeroAPIs.DTT_GLOWSIZE Or AeroAPIs.DTT_TEXTCOLOR
                .crText = ColorTranslator.ToWin32(ForeColor)
                .iGlowSize = GlowSize
            End With

            ' Draw The text on the memory surface.
            AeroAPIs.DrawThemeTextEx(Renderer.Handle, MemHDC, 0, 0, Text, -1, Format, TextRect, TextOptions)

            ' Reflecting the image on the primary surface of the graphics object.
            With ScreenRect
                AeroAPIs.BitBlt(MainHDC, .Left, .Top, .Right - .Left, .Bottom - .Top, MemHDC, 0, 0, AeroAPIs.SRCCOPY)
            End With

            ' Resources Cleaning.
            AeroAPIs.SelectObject(MemHDC, SavedFont)
            AeroAPIs.SelectObject(MemHDC, SavedBitmap)

            AeroAPIs.DeleteDC(MemHDC)
            AeroAPIs.DeleteObject(hFont)
            AeroAPIs.DeleteObject(dibSection)

            Graphics.ReleaseHdc(MainHDC)
        Catch ex As Exception

        End Try
    End Sub
    ''' <summary>
    ''' A method to draw glowing text  with transparenty support if the OS supports it.
    ''' If the OS does not support it then standard GDI text is drawn.
    ''' </summary>
    ''' <param name="graphics">The Graphics object on which to draw.</param>
    ''' <param name="text">The text to draw.</param>
    ''' <param name="font">The font used to draw text.</param>
    ''' <param name="bounds">The bounding rectangle within which to draw.</param>
    ''' <param name="ForeColor">The color used to draw the text.</param>
    ''' <param name="format">The text format flags to apply.</param>
    ''' <param name="glowSize">The size in pixels of the glow around text.</param>
    Public Shared Sub DrawGlowTextWithTransparenty(ByVal Graphics As Graphics, ByVal Text As String, ByVal Font As Font, ByVal bounds As Rectangle, ByVal ForeColor As Color, ByVal Format As TextFormatFlags, ByVal GlowSize As Integer)
        If WindowsAeroEnabled = False Then
            ' Graphics.DrawString(Text, Font, New SolidBrush(ForeColor), bounds.Location)
            bounds.Y -= 3
            TextRenderer.DrawText(Graphics, Text, Font, bounds, ForeColor, Format)
            Exit Sub
        End If
        Dim result As IntPtr = CType(AeroAPIs.S_OK, IntPtr)
        Dim clip As Region = Graphics.Clip
        Dim hRgn As IntPtr = clip.GetHrgn(Graphics)
        Dim sourceDC As IntPtr = Graphics.GetHdc()
        Dim memDC As IntPtr = AeroAPIs.CreateCompatibleDC(sourceDC)
        Dim bmiHdr As New AeroAPIs.BITMAPINFOHEADER()

        bmiHdr.biSize = Marshal.SizeOf(bmiHdr)
        bmiHdr.biBitCount = 32
        bmiHdr.biWidth = bounds.Width
        bmiHdr.biHeight = -bounds.Height
        bmiHdr.biPlanes = 1
        bmiHdr.biCompression = AeroAPIs.BITMAPCOMPRESSION.RGB

        Dim bi As New AeroAPIs.BITMAPINFO()
        bi.bmiHeader = bmiHdr

        Dim dib As IntPtr = AeroAPIs.CreateDIBSection(sourceDC, bi, 0, IntPtr.Zero, IntPtr.Zero, 0)
        AeroAPIs.SelectObject(memDC, dib)

        AeroAPIs.BitBlt(memDC, 0, 0, bounds.Width, bounds.Height, sourceDC, _
         bounds.Left, bounds.Top, AeroAPIs.SRCPAINT)

        Dim hFont As IntPtr = Font.ToHfont()
        Dim originalFont As IntPtr = AeroAPIs.SelectObject(memDC, hFont)

        Dim renderer As New VisualStyleRenderer(VisualStyleElement.CreateElement("globals", 0, 0))

        Dim options As New AeroAPIs.S_DTTOPTS()
        options.dwSize = Marshal.SizeOf(options)
        options.dwFlags = AeroAPIs.DTT_COMPOSITED Or AeroAPIs.DTT_GLOWSIZE Or AeroAPIs.DTT_TEXTCOLOR
        options.crText = ColorTranslator.ToWin32(ForeColor)
        options.iGlowSize = GlowSize

        Dim glowOffset As Integer = GlowSize \ 2

        Dim textBounds As New AeroAPIs.RECT(glowOffset, glowOffset, bounds.Width - GlowSize, bounds.Height - GlowSize)
        result = AeroAPIs.DrawThemeTextEx(renderer.Handle, memDC, 0, 0, Text, -1, _
         Format, textBounds, options)

        If result.ToInt32() = AeroAPIs.S_OK Then
            AeroAPIs.SelectObject(sourceDC, hRgn)
            AeroAPIs.BitBlt(sourceDC, bounds.Left, bounds.Top, bounds.Width, bounds.Height, memDC, _
             0, 0, AeroAPIs.SRCCOPY)
            AeroAPIs.DeleteObject(hRgn)
        End If
        AeroAPIs.SelectObject(sourceDC, originalFont)
        AeroAPIs.DeleteObject(hFont)
        AeroAPIs.DeleteObject(dib)
        AeroAPIs.DeleteDC(memDC)

        Graphics.ReleaseHdc(sourceDC)
    End Sub
    '<AeroGlowLabel>
    Dim Labels(-1) As Label
    ''' <summary>
    ''' Convert a Label to AeroGlowLabel that it can show on Aero.
    ''' </summary>
    ''' <param name="Label">A Label that it convert to AeroGlowLabel.</param>
    Sub ShowLabel(ByVal Label As Label)
        ThrowNothingException(Label, "Label")
        For Each Item In Labels
            If Item.GetHashCode = Label.GetHashCode Then
                Exit Sub
            End If
        Next
        For Each Item In HideLabels
            If Label.GetHashCode = Item Then
                Exit Sub
            End If
        Next
        If AutoSetLabelsTextAlignToTopLeft AndAlso Label.AutoSize = True Then
            Label.TextAlign = Drawing.ContentAlignment.TopLeft
        End If
        Array.Resize(Of Label)(Labels, Labels.Length + 1)
        Labels(Labels.Length - 1) = Label
        AddInvalidateHandles(Label)
        AddHandler Label.Parent.Paint, AddressOf Parents_Paint
    End Sub
    ''' <summary>
    ''' Use for rendering text on Aero.
    ''' </summary>
    Public Enum RenderMode
        ''' <summary>
        ''' Draw with Form graphic.
        ''' </summary>
        ''' <remarks>Must set parent's BackColor to transparent.</remarks>
        Base
        ''' <summary>
        ''' Draw with parent graphic (Has some problems for glow).
        ''' </summary>
        ''' <remarks>Recommand to clear graphic of parent.</remarks>
        Parent
        ''' <summary>
        ''' Draw with parent graphic (Clear old graphic.).
        ''' </summary>
        ParentWithClearPainting
    End Enum
    ''' <summary>
    ''' Gets or sets render mode of rendering text on Aero.
    ''' </summary>
    <Description("Render mode of rendering text on Aero."), Category("Aero"), DefaultValue(GetType(RenderMode), "ParentWithClearPainting")>
    Public Property TextRenderMode As RenderMode = RenderMode.ParentWithClearPainting
    ''' <summary>
    ''' Throw ArgumentNullException if param be nothing.
    ''' </summary>
    ''' <param name="param">An Object that if it be nothing,throw a ArgumentNullException.</param>
    ''' <param name="ParamName">ParamName for throw ArgumentNullException.</param>
    Shared Sub ThrowNothingException(ByRef Param As Object, ByVal ParamName As String)
        If Param Is Nothing Then
            Throw New ArgumentNullException(ParamName)
        End If
    End Sub
    Dim HideLabels(-1) As Integer
    ''' <summary>
    ''' Complete hide a label.Meaning of it is that label can't show even ShowLabel methode call.
    ''' </summary>
    ''' <param name="Label">A Label that after call this methode it can't show.</param>
    ''' <param name="HideLabelNow">If true,HideLabel methode call for the Label.</param>
    Public Sub CompleteHide(ByVal Label As Label, Optional ByVal HideLabelNow As Boolean = True)
        ThrowNothingException(Label, "Label")
        If HideLabelNow Then
            HideLabel(Label)
        End If
        For Each Item In HideLabels
            If Item = Label.GetHashCode Then
                Exit Sub
            End If
        Next
        Array.Resize(Of Integer)(HideLabels, HideLabels.Length + 1)
        HideLabels(HideLabels.Length - 1) = Label.GetHashCode
    End Sub
    ''' <summary>
    ''' Unset CompleteHide of a Label.
    ''' </summary>
    ''' <param name="Label">A Label that unset CompleteHide of it.</param>
    Public Sub UnsetCompleteHide(ByVal Label As Label)
        For i = 0 To HideLabels.GetUpperBound(0)
            If HideLabels(i) = Label.GetHashCode Then
                HideLabels(i) = Nothing
            End If
        Next
        RemoveNothingValues(Of Integer)(HideLabels)
    End Sub
    ''' <summary>
    ''' Convert a AeroGlowLabel to normal Label.
    ''' </summary>
    ''' <param name="Label">A AeroGlowLabel that it convert to normal Label.</param> 
    Sub HideLabel(ByVal Label As Label)
        ThrowNothingException(Label, "Label")
        RemoveInvalidateHandles(Label)
        For i = 0 To Labels.GetUpperBound(0)
            If Label.GetHashCode = Labels(i).GetHashCode Then
                Labels(i) = Nothing
            End If
        Next
        UpdateLabels()
    End Sub
    ''' <summary>
    ''' Add invalidate handles to a label.
    ''' </summary>
    ''' <param name="Label">A Label that invalidate methodes add to it.</param>
    Public Sub AddInvalidateHandles(ByVal Label As Label)
        AddHandler Label.TextChanged, AddressOf Labels_TextChanged
        AddHandler Label.ForeColorChanged, AddressOf Labels_ForeColorChanged
        AddHandler Label.FontChanged, AddressOf Labels_TextChanged
        AddHandler Label.RegionChanged, AddressOf Labels_TextChanged
        AddHandler Label.TextAlignChanged, AddressOf Labels_TextChanged
        AddHandler Label.SizeChanged, AddressOf Labels_TextChanged
        AddHandler Label.LocationChanged, AddressOf Labels_TextChanged
        AddHandler Label.ParentChanged, AddressOf Labels_ParentChanged
    End Sub
    ''' <summary>
    ''' Remove invalidate handles to a label.
    ''' </summary>
    ''' <param name="Label">A Label that invalidate methodes Remove to it.</param>
    Public Sub RemoveInvalidateHandles(ByVal Label As Label)
        RemoveHandler Label.TextChanged, AddressOf Labels_TextChanged
        RemoveHandler Label.ForeColorChanged, AddressOf Labels_ForeColorChanged
        RemoveHandler Label.FontChanged, AddressOf Labels_TextChanged
        RemoveHandler Label.RegionChanged, AddressOf Labels_TextChanged
        RemoveHandler Label.TextAlignChanged, AddressOf Labels_TextChanged
        RemoveHandler Label.SizeChanged, AddressOf Labels_TextChanged
        RemoveHandler Label.LocationChanged, AddressOf Labels_TextChanged
        RemoveHandler Label.ParentChanged, AddressOf Labels_ParentChanged
    End Sub
    Private Sub UpdateLabels()
        RemoveNothingValues(Of Label)(Labels)
    End Sub
    ''' <summary>
    ''' Remove all nothing values of an array.
    ''' </summary>
    ''' <typeparam name="T">Type of your array.</typeparam>
    ''' <param name="Array">An array for update its values.</param>
    Public Sub RemoveNothingValues(Of T)(ByRef Array As T())
        Dim NewArray(-1) As T
        For Each Item In Array
            If Item IsNot Nothing Then
                System.Array.Resize(Of T)(NewArray, NewArray.Length + 1)
                NewArray(NewArray.Length - 1) = Item
            End If
        Next
        Array = NewArray
    End Sub
    ''' <summary>
    ''' Gets or sets Is automatical set Label's TextAlign to TopLeft (If that Label is AutoSize.) for better show in Aero?
    ''' </summary>
    <Description("Is automatical set Label's TextAlign to TopLeft (If that Label is AutoSize.) for better show in Aero?"), Category("Aero"), DefaultValue(False)>
    Public Property AutoSetLabelsTextAlignToTopLeft As Boolean = False
    Private Sub HyperAero_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
        If TextRenderMode <> RenderMode.Base OrElse AeroEnabled = False OrElse DesignMode Then
            Exit Sub
        End If
        For Each Label As Label In Labels
            Dim LabelAlign As TextFormatFlags = GetTextFormatFlags(Label)
            Label.Visible = False
            '   DrawTextGlow2(Label.Parent.CreateGraphics, Label.Text, Label.Font, t, Label.ForeColor, LabelAlign Or TextFormatFlags.NoPrefix, GlowValue)
            '  DrawTextGlow(Label.Parent.CreateGraphics, Label.Text, Label.Font, Label.Bounds, Label.ForeColor, LabelAlign Or TextFormatFlags.NoPrefix, GlowValue)
            Using TLabel As Control = CommonTools.GetActualLocationAsControl(Label)
                Dim t As Rectangle = TLabel.Bounds
                t.Height += 20
                t.Width += 10
                t.Y -= 4
                DrawGlowTextWithTransparenty(e.Graphics, Label.Text, Label.Font, t, Label.ForeColor, LabelAlign, GlowValue)
            End Using
        Next
    End Sub
    Private Sub Parents_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs)
        If TextRenderMode = RenderMode.Base OrElse AeroEnabled = False OrElse DesignMode Then
            Exit Sub
        End If
        Dim ParentC As Control = sender
        Dim LabelsAIP As New Collection
        For Each Label As Label In Labels
            For Each Item In ParentC.Controls
                If Item.GetHashCode = Label.GetHashCode Then
                    LabelsAIP.Add(Item)
                End If
            Next
        Next
        If LabelsAIP.Count = 0 Then
            RemoveHandler ParentC.Paint, AddressOf Parents_Paint
            Exit Sub
        End If
        For Each Label As Label In LabelsAIP
            Dim LabelAlign As TextFormatFlags = GetTextFormatFlags(Label)
            Label.Visible = False
            Dim t As Rectangle = Label.Bounds
            t.Height += 20
            t.Width += 10
            t.Y -= 4
            If TextRenderMode = RenderMode.ParentWithClearPainting Then
                e.Graphics.SetClip(t)
                e.Graphics.Clear(ParentC.BackColor)
                e.Graphics.SetClip(ParentC.CreateGraphics)
            End If
            DrawGlowTextWithTransparenty(e.Graphics, Label.Text, Label.Font, t, Label.ForeColor, LabelAlign, GlowValue)
            '  DrawTextGlow(Label.Parent.CreateGraphics, Label.Text, Label.Font, Label.Bounds, Label.ForeColor, LabelAlign Or TextFormatFlags.NoPrefix, GlowValue)
            'Using TLabel As Control = CommonTools.GetActualLocationAsControl(Label)
            '   DrawTextGlow(e.Graphics, Label.Text, Label.Font, TLabel.Bounds, Label.ForeColor, LabelAlign Or TextFormatFlags.NoPrefix, GlowValue)
            'End Using
        Next
    End Sub
    ''' <summary>
    ''' A method to draw glowing text  with transparenty support if the OS supports it.
    ''' If the OS does not support it then standard GDI text is drawn.
    ''' </summary>
    ''' <param name="graphics">The Graphics object on which to draw.</param>
    ''' <param name="Label" >The label which its properties are used to draw text.</param>
    ''' <param name="GlowValue">The size in pixels of the glow around text.</param>
    Public Shared Sub DrawGlowTextWithTransparenty(ByVal Graphics As Graphics, ByVal Label As Label, ByVal GlowValue As Integer, Optional ByVal NaturalTop As Boolean = True)
        Dim LabelAlign As TextFormatFlags = CommonTools.GetRTLTextOptions(Label).Flags
        Dim t As Rectangle = GetBoundsForGlowText(Label.Bounds, Label.RightToLeft, NaturalTop)
        DrawGlowTextWithTransparenty(Graphics, Label.Text, Label.Font, t, Label.ForeColor, LabelAlign, GlowValue)
    End Sub

    ''' <summary>
    ''' Get the bounds that you must use with DrawGlowTextWithTransparenty method.
    ''' </summary>
    ''' <param name="bounds">The bounding rectangle of your label.</param>
    ''' <param name="RightToLeft">A value indicating whether control's elements are aligned to support locales using right-to-left fonts.</param>
    Public Shared Function GetBoundsForGlowText(ByVal Bounds As Rectangle, Optional ByVal RightToLeft As RightToLeft = Windows.Forms.RightToLeft.No, Optional ByVal NaturalTop As Boolean = True) As Rectangle
        Dim t As Rectangle = Bounds
        t.Height += 20
        If RightToLeft <> Windows.Forms.RightToLeft.Yes Then
            t.Width += 10
        Else
            t.Width += 10
            t.X -= 10
        End If
        t.X += 2
        If NaturalTop Then
            t.Y -= 3
        End If
        Return t
    End Function
    ''' <summary>
    ''' A method to draw glowing text  with transparenty support if the OS supports it.
    ''' If the OS does not support it then standard GDI text is drawn.
    ''' </summary>
    ''' <param name="Options" >Options of drawing text.</param>
    ''' <param name="GlowValue">The size in pixels of the glow around text.</param>
    Public Shared Sub DrawGlowTextWithTransparenty(ByVal Options As TextOptions, ByVal GlowValue As Integer)
        DrawGlowTextWithTransparenty(Options.Graphics, Options.Text, Options.Font, Options.Bounds, Options.ForeColor, Options.Flags, GlowValue)
    End Sub
    ''' <summary>
    ''' Draw text on Aero surface.
    ''' </summary>
    ''' <param name="Location">A Point that represents the point where the text starts.</param>
    ''' <param name="Graphics">The Graphics object on which to draw.</param>
    ''' <param name="Text">The text to draw.</param>
    ''' <param name="Font">The font used to draw text.</param>
    ''' <param name="ForeColor">The color used to draw the text.</param>
    ''' <remarks>Warning:The Font display a little bigger.</remarks>
    Public Shared Sub DrawAeroText(ByVal Graphics As Graphics, ByVal Location As Point, ByVal Text As String, ByVal Font As Font, ByVal ForeColor As Brush, Optional ByVal StringFormat As StringFormat = Nothing)
        If StringFormat Is Nothing Then
            StringFormat = StringFormat.GenericDefault
        End If
        Dim FontPath As New GraphicsPath() 'Font.GetHeight(Graphics)
        FontPath.AddString(Text, Font.FontFamily, CInt(Font.Style), Font.SizeInPoints / 72 * Graphics.DpiX, Location, StringFormat)
        Graphics.SmoothingMode = SmoothingMode.HighQuality
        Graphics.FillPath(ForeColor, FontPath)
        FontPath.Dispose()
    End Sub
    Private Sub Labels_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Invalidate()
    End Sub
    Private Sub Labels_ParentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If sender.parent Is Nothing Then
            Exit Sub
        End If
        AddHandler CType(sender, Label).Parent.Paint, AddressOf Parents_Paint
    End Sub
    Private Sub Labels_ForeColorChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Invalidate(CType(sender, Control).Region)
    End Sub
    '</AeroGlowLabel>
#End Region

#End Region
    ''' <summary>
    ''' Gets or sets Aero Background Enabled (If be true,the background of Form will be Aero frame.).
    ''' It's only work on Windows Vista or above and BackColor is Automatical set to Black.
    ''' </summary>
    <Description("If be true,the background of Form will be Aero frame."), Category("Aero"), DefaultValue(True)>
    Public Property AeroBackgroundEnabled As Boolean = True
    ''' <summary>
    ''' Occurs when Start Animation Finish.
    ''' </summary>
    ''' <param name="Sender">Gets Object that raise this Event.</param>
    <Description("Occurs when Start Animation Finish."), Category("Animation")>
    Public Event AfterStartAnimationFinish(ByVal Sender As Object)
#Region "Enums"
    ''' <summary>
    ''' Indicates whitch mode of an animation start when show and hide window.
    ''' </summary>
    Public Enum AnimationMode
        None
        ShortSlideFade
        LongSlideFade
        Slide
        Fade
    End Enum
    ''' <summary>
    ''' Indicates whitch mode of start when show window.
    ''' </summary>
    Public Enum LocationMode
        None
        Left
        Center
        Right
    End Enum
    ''' <summary>
    ''' Indicates whitch sound play when showing a MSG.
    ''' </summary>
    Public Enum SoundMode
        None
        ErrorSound
        InformationSound
        AlarmSound
        CustomSound
        CustomSoundLocation
    End Enum
#End Region
#Region "Properties"
    ''' <summary>
    ''' Gets or sets custom sound of start.
    ''' </summary>
    <CategoryAttribute("Sound"),
      Description("A sound for playing on start.")>
    Public Property CustomSound As System.IO.Stream
    ''' <summary>
    ''' Gets or sets Location of custom sound of start.
    ''' </summary>
    <CategoryAttribute("Sound"), DefaultValue(""),
   Description("Location of a sound for playing on start.")>
    Public Property CustomSoundLocation As String
    Private speedv As Integer = 20
    ''' <summary>
    ''' Gets or sets fade animation speed.
    ''' Enter a number between 0 - 100.
    ''' </summary>
    <CategoryAttribute("Animation"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(80),
   DesignOnly(False),
   DescriptionAttribute("The speed of fade.")>
    Public Property SpeedOfFade As Integer
        Get
            Return (100 - speedv)

        End Get
        Set(ByVal value As Integer)
            If value >= 100 Then
                value = 99
            End If
            speedv = 100 - value
        End Set
    End Property
    Private speedtgv As Integer = 200
    ''' <summary>
    ''' Gets or sets gradient turning animation speed.
    ''' Enter a number between 0 - 1000.
    ''' </summary>
    <CategoryAttribute("Animation"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(800),
   DesignOnly(False),
   DescriptionAttribute("The speed of gradient turning.")>
    Public Property SpeedOfTurnGradient As Integer
        Get
            Return (1000 - speedtgv)

        End Get
        Set(ByVal value As Integer)
            If value >= 1000 Then
                value = 999
            ElseIf value = 0 Then
                value = 1
            End If
            speedtgv = 1000 - value
            tG.Interval = speedtgv
        End Set
    End Property
    Private speedtgv2 As Integer = 4
    ''' <summary>
    ''' Gets or sets  gradient turning animation speed.
    ''' </summary>
    <CategoryAttribute("Animation"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(4),
   DesignOnly(False),
   DescriptionAttribute("The speed of gradient turning.")>
    Public Property SpeedOfTurnGradient2 As Integer
        Get
            Return speedtgv2

        End Get
        Set(ByVal value As Integer)
            If value = 0 Then
                value = 1
            ElseIf value = 360 Then
                value = 361
            End If
            speedtgv2 = value
        End Set
    End Property

    Private isgv As Boolean = False
    ''' <summary>
    ''' Gets or sets window background gradient enable.
    ''' </summary>
    <CategoryAttribute("Appearance"),
      Browsable(True),
      [ReadOnly](False),
      BindableAttribute(False), DefaultValue(False),
      DesignOnly(False),
    DescriptionAttribute("Is show gradient?")>
    Public Property GradientEnabled As Boolean
        Get
            Return isgv
        End Get
        Set(ByVal value As Boolean)
            isgv = value
            TempGE = value
            Invalidate()
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets start location mode.
    ''' </summary>
    <CategoryAttribute("Layout"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(GetType(LocationMode), "None"),
   DesignOnly(False),
   DescriptionAttribute("The mode of start location.")>
    Public Property StartLocation As LocationMode = LocationMode.None
    Private StartAnimationModev As AnimationMode = AnimationMode.ShortSlideFade
    ''' <summary>
    ''' Gets or sets animation start mode.
    ''' </summary>
    <CategoryAttribute("Animation"),
      Browsable(True),
      [ReadOnly](False),
      BindableAttribute(False), DefaultValue(GetType(AnimationMode), "shortSlideFade"),
      DesignOnly(False),
    DescriptionAttribute("The mode of start animation.")>
    Public Property StartAnimationMode As AnimationMode
        Get
            Return StartAnimationModev
        End Get
        Set(ByVal value As AnimationMode)
            StartAnimationModev = value
        End Set
    End Property
    Private EndAnimationModev As AnimationMode = AnimationMode.Fade
    ''' <summary>
    ''' Gets or sets animation end mode.
    ''' </summary>
    <CategoryAttribute("Animation"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(GetType(AnimationMode), "fade"),
   DesignOnly(False),
   DescriptionAttribute("The mode of end animation.")>
    Public Property EndAnimationMode As AnimationMode
        Get
            Return EndAnimationModev
        End Get
        Set(ByVal value As AnimationMode)
            EndAnimationModev = value
        End Set
    End Property
    Private speedForslidex As Integer = 1
    Private speedForslide2x As Integer = 6
    Private gradientModev As LinearGradientMode = LinearGradientMode.Vertical
    Private ishasgrdmode As Boolean = False

    ''' <summary>
    ''' Gets or sets window gradient mode.
    ''' if you want better option , use gradientAngel.
    ''' </summary>
    <CategoryAttribute("Appearance"), DefaultValue(GetType(LinearGradientMode), "Vertical"),
   DescriptionAttribute("set this or set gradient angel to change gradient angel.")>
    Public Property GradientMode As LinearGradientMode
        Get
            Return gradientModev
        End Get
        Set(ByVal value As LinearGradientMode)
            gradientModev = value
            ishasgrdmode = True
            Invalidate()
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets slide speed.
    ''' set this value smaller to have faster slide.
    ''' </summary>
    <CategoryAttribute("Animation"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(1),
   DesignOnly(False),
   DescriptionAttribute("The speed of slide.(smaller,faster)")>
    Public Property SpeedOfSlide As Integer
        Get
            Return speedForslidex
        End Get
        Set(ByVal value As Integer)
            If value <= 0 Then
                value = 1
            End If
            speedForslidex = value
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets slide speed 2.
    ''' This option can faster slide very good.
    ''' </summary>
    <CategoryAttribute("Animation"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(6),
   DesignOnly(False),
   DescriptionAttribute("You can change speed with this property very good.")>
    Public Property SpeedOfSlide2 As Integer
        Get
            Return speedForslide2x
        End Get
        Set(ByVal value As Integer)
            If value <= 0 Then
                value = 1
            End If
            speedForslide2x = value
        End Set
    End Property
    Private setBlendv As Boolean = False
    ''' <summary>
    ''' Gets or sets set blend enable.
    ''' </summary>
    <CategoryAttribute("Appearance"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(False),
   DesignOnly(False),
   DescriptionAttribute("Is set blend for gradient?")>
    Public Property SetBlend As Boolean
        Get
            Return setBlendv
        End Get
        Set(ByVal value As Boolean)
            setBlendv = value
            Invalidate()
        End Set
    End Property
    Private grdangel As Single = 90
    ''' <summary>
    ''' Gets or sets notify dorm gradient angel.
    ''' </summary>
    <CategoryAttribute("Appearance"), DefaultValue(GetType(Single), "90"),
   DescriptionAttribute("set this or set gradient mode to change gradient angel.")>
    Public Property GradientAngel As Single
        Get
            Return grdangel
        End Get
        Set(ByVal value As Single)
            grdangel = value
            ishasgrdmode = False
            Invalidate()
        End Set
    End Property
    Private TurnGradientEnablev As Boolean = False
    ''' <summary>
    ''' Gets or sets turning gradient enable.
    ''' </summary>
    <CategoryAttribute("Animation"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(False),
   DesignOnly(False),
   DescriptionAttribute("Is show close button in the left of form?")>
    Public Property TurnGradientEnable As Boolean
        Get
            Return TurnGradientEnablev
        End Get
        Set(ByVal value As Boolean)
            TurnGradientEnablev = value
            If DesignMode = False Then
                tG.Enabled = value
            End If
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets window's opacity before Fade Animation.
    ''' </summary>
    <CategoryAttribute("Animation"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(GetType(Double), "0"),
   DesignOnly(False),
   DescriptionAttribute("Window's opacity before Fade Animation.")>
    Public Property BeforeFadeOpacity As Double = 0
    ''' <summary>
    ''' Gets or sets window's opacity after Animation finish.
    ''' </summary>
    <CategoryAttribute("Animation"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(GetType(Double), "1"),
   DesignOnly(False),
   DescriptionAttribute("Window's opacity after Animation finish.")>
    Public Property RealOpacity As Double = 1
    Private blendv As Single = 0.5
    ''' <summary>
    ''' Gets or sets blend value.
    ''' Enter a number between 0-1.
    ''' </summary>
    <CategoryAttribute("Appearance"),
   Browsable(True),
   [ReadOnly](False),
   BindableAttribute(False), DefaultValue(GetType(Single), "0.5"),
   DesignOnly(False),
   DescriptionAttribute("Set the focus number.Enter between 0 and 1.")>
    Public Property BlendValue As Single
        Get
            Return blendv
        End Get
        Set(ByVal value As Single)
            blendv = value
            Invalidate()
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets start sound mode.
    ''' Set it with custom to use CustomSound property.
    ''' </summary>]
    <CategoryAttribute("Sound"),
    Description("Mode of a sound that played on start."),
    DefaultValue(GetType(SoundMode), "None")>
    Public Property StartSoundMode As SoundMode = SoundMode.None
    ''' <summary>
    ''' Gets or sets Speed Of Fading 2.
    ''' </summary>
    <CategoryAttribute("Animation"),
    Description("Value to add to Opacity (Speed Of Fade 2)"),
    DefaultValue(GetType(Double), "0.04")>
    Public Property SpeedOfFade2 As Double = 0.04
    ''' <summary>
    ''' Gets or sets Speed Of End Animation Fading.
    ''' </summary>
    <CategoryAttribute("Animation"),
    Description("Value to remove from Opacity (Speed Of End Fade)"),
    DefaultValue(GetType(Double), "0.2")>
    Public Property SpeedOfEndFade As Double = 0.2
    ''' <summary>
    ''' Gets or sets the Top of windows when Animation is finish.
    ''' </summary>
    <CategoryAttribute("Layout"),
    Description("The Top of windows when Animation is finish."),
    DefaultValue(200)>
    Public Property RealTop As Integer = My.Computer.Screen.Bounds.Height / 2 - Me.Height / 2
    ''' <summary>
    ''' Gets or sets a value indicating whether show Close button.
    ''' </summary>
    <CategoryAttribute("Window Style"),
   Browsable(True),
   [ReadOnly](False),
   DefaultValue(True),
   DesignOnly(False),
   DescriptionAttribute("The tooltip's text.")>
    Public Property CloseBox As Boolean = True
    Dim RealIconv As Icon = My.Resources.FIcon
    ''' <summary>
    ''' Gets or sets icon of window.
    ''' </summary>
    <CategoryAttribute("Window Style"),
   Browsable(True),
   [ReadOnly](False),
   DesignOnly(False),
   DescriptionAttribute("The Icon of the Form.")>
    Public Property RealIcon As Icon
        Get
            Return RealIconv
        End Get
        Set(ByVal value As Icon)
            RealIconv = value
            Me.Icon = RealIcon
        End Set
    End Property
    ''' <summary>
    ''' Gets or sets indicating whether Active window when window's vivible equal True.
    ''' </summary>
    <CategoryAttribute("Appearance"),
   Browsable(True),
   [ReadOnly](False),
   DesignOnly(False),
   DefaultValue(True),
   DescriptionAttribute("Indicating whether Active window when window's vivible equal True.")>
    Public Property StartupActive As Boolean = True
#End Region
    Dim MouseOffset As Point
    Private Sub Movable_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        DragMove()
    End Sub
    Private Sub AeroMovable_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        If AeroEnabled = False Then
            Exit Sub
        End If
        DragMove()
    End Sub
    Private Sub AeroBMovable_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        If AeroEnabled = False AndAlso IsBasicTheme = False Then
            Exit Sub
        End If
        DragMove()
    End Sub
    Private Sub AeroMarginMovable_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        If NowInAero = False Then
            Exit Sub
        End If
        DragMove()
    End Sub
    ''' <summary>
    ''' Gets is Basic theme active.
    ''' </summary>
    Public Shared ReadOnly Property IsBasicTheme As Boolean
        Get
            Return CommonTools.IsBasicTheme
        End Get
    End Property
    ''' <summary>
    ''' Gets best color for Aero area in Windows XP or in Basic theme.
    ''' </summary>
    ''' <param name="AeroColor">A value that it return if AeroEnabled be false.</param>
    Public Function GetAeroAreaColor(Optional ByVal AeroColor As Color = Nothing) As Color
        Return CommonTools.GetAeroAreaColor(ActiveForm Is Me, AeroEnabled, AeroColor)
    End Function
    ''' <summary>
    ''' Gets best color for Aero area in Windows XP or in Basic theme.
    ''' </summary>
    ''' <param name="Focused">A value that show Form is active or not.</param>
    ''' <param name="AeroEnabled">A value that if be true,return AeroColor.</param>
    ''' <param name="AeroColor">A value that it return if AeroEnabled be false.</param>
    Public Shared Function GetAeroAreaColor(ByVal Focused As Boolean, Optional ByVal AeroEnabled As Boolean = False, Optional ByVal AeroColor As Color = Nothing) As Color
        Return CommonTools.GetAeroAreaColor(Focused, AeroEnabled, AeroColor)
    End Function
    ''' <summary>
    ''' Gets Is now mouse in Aero area?
    ''' </summary>
    Public ReadOnly Property NowInAero As Boolean
        Get
            Dim clientPoint As Point = Me.PointToClient(New Point(MousePosition.X, MousePosition.Y))
            If IsOutsideMargins(clientPoint, ClientSize) = True Then
                clientPoint = Nothing
                Return False
            End If
            clientPoint = Nothing
            Return True
        End Get
    End Property
    ''' <summary>
    ''' Gets Is now a point in Aero area?
    ''' </summary>
    Public ReadOnly Property NowInAero(ByVal Location As Point) As Boolean
        Get
            If IsOutsideMargins(Location, ClientSize) = True Then
                Return False
            End If
            Return True
        End Get
    End Property
    ''' <summary>
    ''' Set a Control to move Form if user click and drag it.
    ''' </summary>
    ''' <param name="Control">A Control that if user click and drag it,Move Form.</param>
    Public Sub AddMovableControl(ByVal Control As Control)
        AddHandler Control.MouseDown, AddressOf Movable_MouseDown
    End Sub
    ''' <summary>
    ''' Set a Control to move Form if user click and drag it (Only if AeroEnabled is true).
    ''' </summary>
    ''' <param name="Control">A Control that if user click and drag it,Move Form.</param>
    Public Sub AddAeroMovableControl(ByVal Control As Control)
        AddHandler Control.MouseDown, AddressOf AeroMovable_MouseDown
    End Sub
    ''' <summary>
    ''' Set a Control to move Form if user click and drag it (Only if AeroEnabled is true and the Control is in the Aero Margins).
    ''' </summary>
    ''' <param name="Control">A Control that if user click and drag it,Move Form.</param>
    Public Sub AddAeroMarginMovableControl(ByVal Control As Control)
        AddHandler Control.MouseDown, AddressOf AeroMarginMovable_MouseDown
    End Sub
    ''' <summary>
    ''' Set a Control to move Form if user click and drag it (Only if AeroEnabled is true or Basic theme is active).
    ''' </summary>
    ''' <param name="Control">A Control that if user click and drag it,Move Form.</param>
    Public Sub AddAeroOrBasicMovableControl(ByVal Control As Control)
        AddHandler Control.MouseDown, AddressOf AeroBMovable_MouseDown
    End Sub
    ''' <summary>
    ''' Unset a Control for move Form if user click and drag it.
    ''' </summary>
    ''' <param name="Control">A Control that unset from Form Movable Controls.</param>
    Public Sub RemoveMovableControl(ByVal Control As Control)
        RemoveHandler Control.MouseDown, AddressOf Movable_MouseDown
    End Sub
    ''' <summary>
    ''' Unset a Control for move Form if user click and drag it (Only if AeroEnabled is true or Basic theme is active).
    ''' </summary>
    ''' <param name="Control">A Control that unset from Form Movable Controls.</param>
    Public Sub RemoveAeroOrBasicMovableControl(ByVal Control As Control)
        RemoveHandler Control.MouseDown, AddressOf AeroBMovable_MouseDown
    End Sub
    ''' <summary>
    ''' Unset a Control for move Form if user click and drag it (Only if AeroEnabled is true).
    ''' </summary>
    ''' <param name="Control">A Control that unset from Form Movable Controls.</param>
    Public Sub RemoveAeroMovableControl(ByVal Control As Control)
        RemoveHandler Control.MouseDown, AddressOf AeroMovable_MouseDown
    End Sub
    ''' <summary>
    ''' Unset a Control for move Form if user click and drag it (Only if AeroEnabled is true and the Control is in the Aero Margins).
    ''' </summary>
    ''' <param name="Control">A Control that unset from Form Movable Controls.</param>
    Public Sub RemoveAeroMarginMovableControl(ByVal Control As Control)
        RemoveHandler Control.MouseDown, AddressOf AeroMarginMovable_MouseDown
    End Sub
    Protected Overrides ReadOnly Property ShowWithoutActivation As Boolean
        Get
            Return Not StartupActive
        End Get
    End Property
    Protected Overrides ReadOnly Property CreateParams() As CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            Const CS_NOCLOSE As Integer = &H200
            If CloseBox = True Then
                cp.ClassStyle = cp.ClassStyle
            Else
                cp.ClassStyle = cp.ClassStyle Or CS_NOCLOSE
            End If
            Return cp
        End Get
    End Property
    ''' <summary>
    ''' Convert colorblend to grayscale if Disabled else return origional colorblend
    ''' </summary>
    ''' <param name="ColorIn">Colorblend to Check</param>
    Private Function EnableBlends(ByVal ColorIn As Color()) As Color()

        If Me.Enabled Then
            Return ColorIn
        Else
            Dim tcolor As New List(Of Color)
            For Each c As Color In ColorIn
                Dim gray As Integer = CInt(c.R * 0.3 + c.G * 0.59 + c.B * 0.11)
                tcolor.Add(Color.FromArgb(c.A, gray, gray, gray))
            Next
            Return tcolor.ToArray
        End If
    End Function
    'BMK OnPaint
    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
        If GradientEnabled = True Then
            Dim rect As Rectangle
            Dim gr As Graphics = e.Graphics
            Dim Op As New GradientOptions
            With Op
                .Enabled = Enabled
                .GradientAngel = GradientAngel
                .GradientMode = GradientMode
                .UseGradientMode = ishasgrdmode
                .GradientType = GradientType.Radial
            End With
            If BackgroundControl IsNot Nothing AndAlso BackgroundControl.Length > 0 Then
                For Each BackgroundControlItem In BackgroundControl
                    rect = New Rectangle(CommonTools.GetActualLocation(BackgroundControlItem), BackgroundControlItem.ClientSize)
                    GradientBlend.DrawGradient(e.Graphics, BackgroundGradient, rect, Op)
                Next
            Else
                rect = ClientRectangle
                GradientBlend.DrawGradient(e.Graphics, BackgroundGradient, rect, Op)
            End If
        End If
        RefeshFrame(e.Graphics)
        MyBase.OnPaint(e)
    End Sub



    Private Sub RefeshFrame(ByVal Graphics As Graphics)
        If IsEtendingFrameInNonAero Then
            Graphics.FillRectangles(New SolidBrush(CurrentCaptionColor), AeroMargins.ToRectangles(Me))
        End If
    End Sub
    ''' <summary>
    ''' Gets an array of rectangles of Aero area.
    ''' </summary>
    Public ReadOnly Property AeroArea As Rectangle()
        Get
            Return AeroMargins.ToRectangles(Me)
        End Get
    End Property
    ''' <summary>
    ''' Gets or sets mode of drawing caption bar (Force active).
    ''' </summary>
    <Description("Mode of drawing caption bar (Force active)."), Category("Window Style"), DefaultValue(GetType(CaptionBarStates), "AutoSet")>
    Public Overridable Property CaptionBarRenderMode As CaptionBarStates = CaptionBarStates.AutoSet
    Public Sub New()
        'Enable using this form in WPF
        Application.EnableVisualStyles()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        ' SetWindowThemeAttributes(AeroAPIs.WTNCA.NODRAWCAPTION Or AeroAPIs.WTNCA.NODRAWICON)
    End Sub
    ''' <summary>
    ''' Set some advanced options of this Form in Windows Vista or later with Aero enabled.
    ''' </summary>
    ''' <param name="Attributes">Advanced options of this Form.</param>
    Public Sub SetWindowThemeAttributes(ByVal Attributes As AeroAPIs.WTNCA)
        ' This tests that the OS will support what we want to do. Will be false on Windows XP and earlier,
        ' as well as on Vista and 7 with Aero Glass disabled.
        If Not WindowsAeroEnabled Then
            Return
        End If
        Dim options As New AeroAPIs.WTA_OPTIONS()
        options.dwFlags = Attributes
        options.dwMask = AeroAPIs.WTNCA.VALIDBITS
        ' The SetWindowThemeAttribute API call takes care of everything
        AeroAPIs.SetWindowThemeAttribute(Me.Handle, AeroAPIs.WINDOWTHEMEATTRIBUTETYPE.WTA_NONCLIENT, options, CUInt(Marshal.SizeOf(GetType(AeroAPIs.WTA_OPTIONS))))
    End Sub
    Private Sub Fsh_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        RealShow = True
        Me.Icon = RealIcon
        If DesignMode = True Then
            Me.Opacity = 100
            Exit Sub
        End If
        Me.Opacity = 0
        UpdateRealTop()
        If TurnGradientEnablev = True Then
            Me.tG.Enabled = True
        End If
        RealBackGroundImage = Me.BackgroundImage
        ResetAeroBackground()
        If AeroEnabled = True Then
            ReShowLabels()
        End If
        If WindowsAeroEnabled = False Then
            RaiseEvent AeroEffectDisabled(Me, New EventArgs())
        End If
    End Sub
    ''' <summary>
    ''' Convert all AeroGlowLabels to Labels and reconvert all Labels to AeroGlowLabels (If AutoshowLabels be True).
    ''' </summary>
    Public Overridable Sub ReShowLabels()
        If AutoShowLabels Then
            Labels = New Label(-1) {}
            ShowAllLabels()
        End If
    End Sub
#Region "Ticks"
    '  Dim Designmode As Boolean = True
    Private Sub t1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles t1.Tick
        If DesignMode = True Then
            Exit Sub
        End If
        If Me.Opacity >= RealOpacity Then
            t1.Enabled = False
            If tsh.Enabled = False Then
                RaiseEvent AfterStartAnimationFinish(Me)
            End If
            Exit Sub
        Else
            Me.Opacity = Me.Opacity + SpeedOfFade2
        End If
    End Sub

    Private Sub tsh_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsh.Tick
        If DesignMode = True Then
            Exit Sub
        End If
        If Me.Top <= RealTop Then
            tsh.Enabled = False
            If t1.Enabled = False Then
                RaiseEvent AfterStartAnimationFinish(Me)
            End If
            Exit Sub
        End If
        Me.Top = Me.Top - SpeedOfSlide2
    End Sub

    Private Sub tend_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tend.Tick
        If DesignMode = True Then
            Exit Sub
        End If
        t1.Enabled = False
        tend.Interval = speedv
        Select Case EndAnimationMode
            Case AnimationMode.Fade
                tendf.Enabled = True
                tend.Enabled = False
            Case AnimationMode.Slide
                If Me.Top = (My.Computer.Screen.Bounds.Height - 2) Then
                    tend.Enabled = False
                    RealClose = True
                    Me.Close()
                    Exit Sub
                End If
                Me.Top = Me.Top + SpeedOfSlide2
            Case Else 'animationMode.shortSlideFade Or animationMode.longSlideFade
                If isstart = False Then
                    tendf.Enabled = True
                End If
                If Me.Top = (My.Computer.Screen.Bounds.Height - 2) Then
                    tend.Enabled = False
                    Exit Sub
                End If
                Me.Top = Me.Top + SpeedOfSlide2
        End Select

    End Sub
    Dim isstart As Boolean = False
    Protected Property RealClose As Boolean = False
    Dim RealHide As Boolean = False
    Dim RealShow As Boolean = True
    Public Overloads Sub Close()
        If AnimationVisible = False Then
            RealHide = True
            Me.Visible = False
            RealShow = True
            tend.Enabled = False
            tendf.Enabled = False
            RealClose = False
            Exit Sub
        End If
        MyBase.Close()
    End Sub
    Overloads Sub Show(Optional ByVal Owner As System.Windows.Forms.IWin32Window = Nothing)
        RealShow = True
        tend.Enabled = False
        tendf.Enabled = False
        If Owner IsNot Nothing Then
            MyBase.Show(Owner)
        Else
            MyBase.Show()
        End If
    End Sub

    Private Sub tendf_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tendf.Tick
        If DesignMode = True Then
            Exit Sub
        End If
        isstart = True
        If Me.Opacity <= 0 Then
            tend.Enabled = False
            isstart = False
            RealClose = True
            Me.Close()
        Else
            Me.Opacity = Me.Opacity - SpeedOfEndFade
        End If
    End Sub

    Private Sub tn_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tn.Tick
        If DesignMode = True Then
            Exit Sub
        End If
        tendf.Interval = SpeedOfSlide2 * 3
        t1.Interval = SpeedOfSlide2
        tsh.Interval = SpeedOfSlide
        tn.Enabled = False
    End Sub
    Dim isturn As Boolean
    Private Sub tG_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tG.Tick
        If ishasgrdmode = True Then
            Select Case GradientMode
                Case LinearGradientMode.Vertical
                    GradientAngel = 90
                Case LinearGradientMode.ForwardDiagonal
                    GradientAngel = 45
                Case LinearGradientMode.BackwardDiagonal
                    GradientAngel = -230
                Case LinearGradientMode.Horizontal
                    GradientAngel = 0
            End Select
        End If
        ishasgrdmode = False
        If grdangel = 361 Then
            isturn = True
        ElseIf grdangel = -361 Then
            isturn = False
        End If
        If isturn = True Then
            grdangel = grdangel - SpeedOfTurnGradient2
        Else
            grdangel = grdangel + SpeedOfTurnGradient2
        End If
        Invalidate()
    End Sub
#End Region
    ''' <summary>
    ''' Occurs after Form Closing Animation finish.
    ''' </summary>
    ''' <param name="Sender">A copy of sender Object.</param>
    ''' <param name="e">A Ref of FormClosingEventArgs Object in FormClosing Event.</param>
    <Category("Behavior"),
    Description("Occurs after Form Closing Animation finish.")>
    Public Event RealClosing(ByVal Sender As Object, ByRef e As FormClosingEventArgs)
    ''' <summary>
    ''' Occurs before Form Closing Event called.
    ''' </summary>
    ''' <param name="Sender">A copy of sender Object.</param>
    ''' <param name="e">Set e.Cancel to True to Disable Closing Ainimations.</param>
    <Category("Behavior"),
    Description(" Occurs before Form Closing Event called.")>
    Public Event BeforeFormClosing(ByVal Sender As Object, ByVal e As CancelEventArgs)
    Private Sub Fsh_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If DesignMode = True Then
            Exit Sub
        End If
        Dim Ce As New CancelEventArgs()
        RaiseEvent BeforeFormClosing(Me, Ce)
        If Ce.Cancel = True Then
            e.Cancel = True
            Exit Sub
        End If
        t1.Enabled = False
        tsh.Enabled = False
        If RealClose = False Then
            tend.Enabled = True
            tend.Interval = 1
            e.Cancel = True
        Else
            t1.Enabled = False
            tsh.Enabled = False
            tend.Enabled = False
            tendf.Enabled = False
            tG.Enabled = False
            tn.Enabled = False
            RaiseEvent RealClosing(sender, e)
        End If
        RealClose = False
    End Sub

#Region "Subs"
    ''' <summary>
    ''' Select a control by its Name.
    ''' </summary>
    ''' <param name="Name">Name of Control.</param>
    Public Function SelectControl(ByVal Name As String)
        For Each Item As Control In Controls
            If Item.Name = Name Then
                Return Item
            End If
            If Item.Controls.Count > 0 Then
                Dim Result As Control = SelectControlInCollection(Name, Item.Controls)
                If Result IsNot Nothing Then
                    Return Result
                End If
            End If
        Next
        Return Nothing
    End Function
    ''' <summary>
    ''' Select a control by its Name in a Control Colection.
    ''' </summary>
    ''' <param name="Name">The Name of control.</param>
    ''' <param name="Collection">The Colection that contains Control.</param>
    Public Function SelectControlInCollection(ByVal Name As String, ByRef Collection As Control.ControlCollection)
        For Each Item As Control In Collection
            If Item.Name = Name Then
                Return Item
            End If
            If Item.Controls.Count > 0 Then
                Return SelectControlInCollection(Name, Item.Controls)
            End If
        Next
        Return Nothing
    End Function
    Private Sub ShowAllLabels()
        For Each Item As Control In Controls
            If TypeOf Item Is Label Then
                ShowLabel(Item)
            End If
            If Item.Controls.Count > 0 Then
                ShowLabelsInCollection(Item.Controls)
            End If
        Next
    End Sub
    Private Sub ShowLabelsInCollection(ByRef Collection As Control.ControlCollection)
        For Each Item As Control In Collection
            If TypeOf Item Is Label Then
                ShowLabel(Item)
            End If
            If Item.Controls.Count > 0 Then
                ShowLabelsInCollection(Item.Controls)
            End If
        Next
    End Sub
#Region "Get a type"
    ''' <summary>
    ''' Return an Collection of T that they are in Form.Controls.
    ''' </summary>
    Public Function GetsATypeAsCollection(Of T As Control)() As Collection
        Return GetATypeAsCollection(Of T)(Me)
    End Function
    ''' <summary>
    ''' Return an Collection of T that they are in Control.Controls.
    ''' </summary>
    Public Shared Function GetATypeAsCollection(Of T As Control)(ByVal Control As Control) As Collection
        Dim Returned As New Collection
        For Each Item As Control In Control.Controls
            If TypeOf Item Is T Then
                Returned.Add(Item)
            End If
            If Item.Controls.Count > 0 Then
                HelperGetAType(Of T)(Control, Returned, Item.Controls)
            End If
        Next
        Return Returned
    End Function
    ''' <summary>
    ''' Return an Array of T that they are in Form.Controls.
    ''' </summary>
    Public Function GetAType(Of T As Control)() As T()
        Return GetAType(Of T)(Me)
    End Function
    ''' <summary>
    ''' Return an Array of T that they are in Control.Controls.
    ''' </summary>
    Public Shared Function GetAType(Of T As Control)(ByVal Control As Control) As T()
        Dim Returned As Collection = GetATypeAsCollection(Of T)(Control)
        Dim RR(Returned.Count - 1) As T
        For i = 1 To Returned.Count
            RR(i - 1) = Returned(i)
        Next
        Return RR
    End Function
    Private Shared Sub HelperGetAType(Of T)(ByVal Control As Control, ByRef Returned As Collection, ByRef Collection As Control.ControlCollection)
        For Each Item As Control In Collection
            If TypeOf Item Is T Then
                Returned.Add(Item)
            End If
            If Item.Controls.Count > 0 Then
                HelperGetAType(Of T)(Control, Returned, Item.Controls)
            End If
        Next
    End Sub
#End Region

    ''' <summary>
    ''' Create an Array of Anything.
    ''' </summary>
    ''' <typeparam name="T">Type of Array.</typeparam>
    ''' <param name="Array">The Array that returned.</param>
    ''' <returns>An Array of T.</returns>
    Public Shared Function CreateArray(Of T)(ByVal ParamArray Array As T()) As T()
        Return Array
    End Function
    ''' <summary>
    ''' ShutDown Computer.
    ''' </summary>
    ''' <param name="Wait">Wait Time for doing this operating.</param>
    Public Shared Sub ShutDown(Optional ByVal Wait As Integer = 0)
        Shell("Shutdown -s -f -t" + Str(Wait), AppWinStyle.Hide)
    End Sub
    ''' <summary>
    ''' Restart Computer.
    ''' </summary>
    ''' <param name="Wait">Wait Time for doing this operating.</param>
    Public Shared Sub Restart(Optional ByVal Wait As Integer = 0)
        Shell("Shutdown -r -f -t" + Str(Wait), AppWinStyle.Hide)
    End Sub
    ''' <summary>
    ''' Log off current user.
    ''' </summary>
    Public Shared Sub LogOff()
        Process.Start("Logoff.exe")
    End Sub
    ''' <summary>
    ''' Hibernate Computer.
    ''' </summary>
    Public Shared Sub Hibernate()
        Application.SetSuspendState(PowerState.Hibernate, True, True)
    End Sub
    ''' <summary>
    ''' Stand by (Sleep)Computer.
    ''' </summary>
    Public Shared Sub StandBy()
        Application.SetSuspendState(PowerState.Suspend, True, False)
    End Sub
    ''' <summary>
    ''' Cancel All Turn Off operating.
    ''' </summary>
    ''' <param name="Wait">Wait Time for doing this operating.</param>
    Public Shared Sub CancelTurnOff(Optional ByVal Wait As Integer = 0)
        Shell("Shutdown -a -f -t" + Str(Wait), AppWinStyle.Hide)
    End Sub
    ''' <summary>
    ''' Gets the current Power status.
    ''' If power is plugged in,Return True,Else return False.
    ''' </summary>
    Public Shared ReadOnly Property PowerPluggedIn As Boolean
        Get
            If SystemInformation.PowerStatus.PowerLineStatus = 1 Then
                Return True
            Else
                Return False
            End If
        End Get
    End Property
    ''' <summary>
    ''' Gets the approximate percentage of full battery time remaining.
    ''' </summary>
    Public Shared ReadOnly Property BatteryLifePercent As Single
        Get
            Return SystemInformation.PowerStatus.BatteryLifePercent
        End Get
    End Property
    ''' <summary>
    ''' Gets the user name associated with current thread.
    ''' </summary>
    Public Shared ReadOnly Property UserName As String
        Get
            Return SystemInformation.UserName
        End Get
    End Property
    ''' <summary>
    ''' Gets the current battery charge status.
    ''' </summary>
    Public Shared ReadOnly Property BatteryChargeStatus As BatteryChargeStatus
        Get
            Return SystemInformation.PowerStatus.BatteryChargeStatus
        End Get
    End Property
    ''' <summary>
    ''' Lock current user.
    ''' </summary>
    Public Shared Sub LockSystem()
        Shell("rundll32 user32.dll,LockWorkStation", AppWinStyle.NormalFocus)
    End Sub
#End Region
    Dim WithEvents BG As BackgroundWorker
    Dim AnimationVisible As Boolean = True
    Private Sub Fsh_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.VisibleChanged
        If DesignMode = True Then 'Or RealHide = True Then
            Exit Sub
        End If
        If AutoAeroChange AndAlso Visible Then
            BG = New BackgroundWorker
            BG.RunWorkerAsync()
            BG.Dispose()
            BG = Nothing
        End If
        If Visible = False And RealHide = False Then
            AnimationVisible = False
            tend.Interval = 1
            tend.Enabled = True
            RealShow = False
            Me.Visible = True
            Exit Sub
        End If
        If RealShow = False Then
            Exit Sub
        End If
        AnimationVisible = True
        RealHide = False
        UpdateRealTop()
        'Sound
        Dim s As New System.Media.SoundPlayer
        Select Case StartSoundMode
            Case SoundMode.InformationSound
                My.Computer.Audio.Stop()
                My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Asterisk)
            Case SoundMode.ErrorSound
                My.Computer.Audio.Stop()
                My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Hand)
            Case SoundMode.AlarmSound
                My.Computer.Audio.Stop()
                My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Exclamation)
            Case SoundMode.CustomSound
                If CustomSound Is Nothing Then
                    Throw New ArgumentNullException("CustomSound")
                End If
                s.Stream = CustomSound
                s.Load()
                s.Stop()
                s.Play()
            Case SoundMode.CustomSoundLocation
                If Not My.Computer.FileSystem.FileExists(CustomSoundLocation) Then
                    Throw New IO.FileNotFoundException("Custom sound location doesn't exist.", CustomSoundLocation)
                End If
                s.SoundLocation = CustomSoundLocation
                s.Load()
                s.Stop()
                s.Play()
        End Select
        '\Sound
        tsh.Enabled = True
        t1.Enabled = True
        tn.Enabled = True
        Me.Opacity = BeforeFadeOpacity
        Select Case StartAnimationMode
            Case AnimationMode.ShortSlideFade
                Me.Top = My.Computer.Screen.Bounds.Height - (Me.Height - 20)
            Case AnimationMode.LongSlideFade
                Me.Top = My.Computer.Screen.Bounds.Height
            Case AnimationMode.Fade
                tsh.Enabled = False
                Me.Top = RealTop 'My.Computer.Screen.Bounds.Height / 2 - Me.Height / 2
            Case AnimationMode.Slide
                t1.Enabled = False
                Me.Opacity = RealOpacity
                Me.Top = My.Computer.Screen.Bounds.Height
            Case AnimationMode.None
                Me.Opacity = RealOpacity
                t1.Enabled = False
                Me.Top = RealTop
        End Select
        Select Case StartLocation
            Case LocationMode.Right
                Me.Left = My.Computer.Screen.Bounds.Width - (Me.Width + 50)
            Case LocationMode.Left
                Me.Left = 50
            Case LocationMode.Center
                Me.Left = (My.Computer.Screen.Bounds.Width / 2) - (Me.Width / 2 + 50)
        End Select
        tendf.Interval = speedv * 3
        t1.Interval = speedv
    End Sub
    ''' <summary>
    ''' Update RealTop property.
    ''' </summary>
    Public Sub UpdateRealTop()
        If Me.StartPosition = FormStartPosition.CenterScreen Then
            Me.RealTop = My.Computer.Screen.Bounds.Height / 2 - Me.Height / 2
        ElseIf Me.StartPosition = FormStartPosition.CenterParent Then
            Me.RealTop = ParentForm.Top + ParentForm.Height / 2 - Me.Height / 2
        End If
    End Sub
    Private Sub BG_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BG.DoWork
        On Error Resume Next
        Threading.Thread.Sleep(300)
        ResetAeroBackground()
    End Sub

    Private Sub HyperAero_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
        If DragForm Then
            DragMove()
        End If
    End Sub

    Private Sub HyperAero_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        If Visible Then
            Invalidate(AeroMargins.NonArea(Me))
        End If
        If ExceptAeroEnabled Then
            ResetAeroBackground()
        End If
    End Sub
    ''' <summary>
    ''' Gets is frame of windows is extending in Windows XP or in Basic theme.
    ''' </summary>
    Public ReadOnly Property IsEtendingFrameInNonAero As Boolean
        Get
            Return False
            ' Return Not WindowsAeroEnabled AndAlso AeroBackgroundEnabled()
        End Get
    End Property
    Public Declare Function GetSysColor Lib "user32" _
Alias "GetSysColor" (ByVal nIndex As Integer) As Integer
    Private COLOR_ACTIVECAPTION As Integer = 2
    Private COLOR_GRADIENTACTIVECAPTION As Integer = 27

    'BMK PaintNCA
    Private Sub HyperAero_PaintNonClientArea(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.PaintNonClientArea
        If IsEtendingFrameInNonAero AndAlso CommonTools.IsBasicTheme = False AndAlso Visible Then
            Dim Clc As New Rectangle(New Point(3, 5), New Size(Width - CaptionButtonSize.Width * 3 - 2, CaptionHeight))
            Dim Rtb As New LinearGradientBrush(Clc, Color.Transparent, Color.FromArgb(255, CurrentCaptionColor), LinearGradientMode.Vertical)
            e.Graphics.FillRectangle(Rtb, Clc)
            Dim Rl As New Rectangle(0, CaptionHeight, 5, Height - CaptionHeight)
            Dim Rlb As New LinearGradientBrush(Rl, Color.Transparent, Color.FromArgb(255, CurrentCaptionColor), LinearGradientMode.Horizontal)
            e.Graphics.FillRectangle(Rlb, Rl)
            Dim Rr As New Rectangle(Width - 5, 0, 5, Height)
            Dim Rrb As New LinearGradientBrush(Rr, Color.FromArgb(255, CurrentCaptionColor), Color.Transparent, LinearGradientMode.Horizontal)
            e.Graphics.FillRectangle(Rrb, Rr)
            Dim Rb As New Rectangle(New Point(0, Height - 4), New Size(Width, 3))
            Dim Rbb As New LinearGradientBrush(Rb, Color.Transparent, Color.FromArgb(255, CurrentCaptionColor), LinearGradientMode.Vertical)
            e.Graphics.FillRectangle(Rbb, Rb)
            ' Dim Rb As New Rectangle(0, CaptionHeight, 5, Height)
        End If
    End Sub
    ''' <summary>
    ''' Gets title bar height of this Form.
    ''' </summary>
    Public ReadOnly Property CaptionHeight As Integer
        Get
            If Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedToolWindow OrElse Me.FormBorderStyle = Windows.Forms.FormBorderStyle.SizableToolWindow Then
                Return SystemInformation.ToolWindowCaptionHeight
            Else
                Return SystemInformation.CaptionHeight
            End If
        End Get
    End Property
    ''' <summary>
    ''' Gets size of title bar's buttons in this Form.
    ''' </summary>
    Public ReadOnly Property CaptionButtonSize As Size
        Get
            If Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedToolWindow OrElse Me.FormBorderStyle = Windows.Forms.FormBorderStyle.SizableToolWindow Then
                Return SystemInformation.ToolWindowCaptionButtonSize
            Else
                Return SystemInformation.CaptionButtonSize
            End If
        End Get
    End Property
    Friend ReadOnly Property CurrentCaptionColor As Color
        Get
            If Visible = False OrElse DesignMode Then
                Return SystemColors.ActiveCaption
            End If
            If IsEtendingFrameInNonAero AndAlso CommonTools.IsBasicTheme = False Then
                Dim Sc As New ScreenCapture
                Dim WImage As Bitmap = Sc.CaptureWindow(Me.Handle)
                Return WImage.GetPixel(5, CaptionHeight - If(FormBorderStyle <> Windows.Forms.FormBorderStyle.SizableToolWindow AndAlso FormBorderStyle <> Windows.Forms.FormBorderStyle.FixedToolWindow, 10, 4))
            Else
                Return GetAeroAreaColor(Color.Transparent)
            End If
        End Get
    End Property
    Private Delegate Sub EasyAction()
    Private Sub HyperAero_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown, Me.Activated, Me.Deactivate
        Dim Ca As New CallAfter
        Ca.CallAfter(500, New EasyAction(AddressOf InvalidateNonClientArea))
    End Sub


End Class
Public Class AeroAPIs
    Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByRef lParam As Object) As Integer
    Public Const WS_CHILD As UInteger = &H40000000
    Public Const WS_EX_LAYERED As UInteger = &H80000
    Public Const WS_CLIPSIBLINGS As UInteger = &H4000000
    Public Const WM_ACTIVATEAPP As UInteger = 28
    <StructLayout(LayoutKind.Sequential)> _
    Public Structure WTA_OPTIONS
        Public dwFlags As WTNCA
        Public dwMask As WTNCA
    End Structure

    <Flags()> _
    Public Enum WTNCA As UInteger
        NODRAWCAPTION = 1
        NODRAWICON = 2
        NOSYSMENU = 4
        NOMIRRORHELP = 8
        VALIDBITS = NODRAWCAPTION Or NODRAWICON Or NOSYSMENU Or NOMIRRORHELP
    End Enum

    Public Enum WINDOWTHEMEATTRIBUTETYPE As UInteger
        ''' <summary>Non-client area window attributes will be set.</summary>
        WTA_NONCLIENT = 1
    End Enum

    <DllImport("uxtheme.dll")> _
    Public Shared Function SetWindowThemeAttribute(ByVal hWnd As IntPtr, ByVal wtype As WINDOWTHEMEATTRIBUTETYPE, ByRef attributes As WTA_OPTIONS, ByVal size As UInteger) As Integer
    End Function
    <DllImport("user32.dll", EntryPoint:="SystemParametersInfo")> _
    Public Shared Function SystemParametersInfo(ByVal uiAction As UInteger, ByVal uiParam As UInteger, ByVal pvParam As UInteger, ByVal fWinIni As UInteger) As Boolean
    End Function
    Declare Function GetDesktopWindow Lib "user32.dll" () As IntPtr
    Public Const SC_CONTEXTHELP As Int32 = &HF180

    Public Const MF_REMOVE = &H1000&
    Public Const MF_BYCOMMAND As Int32 = &H0I
    Public Const MF_STRING As Int32 = &H0I
    Public Const MF_BYPOSITION = &H400&

    Public Const WM_SYSCOMMAND As Int32 = &H112 ' System menu 
    Public Const WM_SIZE As Integer = 5
    Public Const WM_SYNCPAINT As Integer = 136
    Public Const WM_MOVE As Integer = 3
    Public Const WM_ACTIVATE As Integer = 6
    Public Const WM_LBUTTONDOWN As Integer = 513
    Public Const WM_LBUTTONUP As Integer = 514
    Public Const WM_LBUTTONDBLCLK As Integer = 515
    Public Const WM_MOUSEMOVE As Integer = 512
    Public Const WM_PAINT As Integer = 15
    Public Const WM_GETTEXT As Integer = 13
    Public Const WM_NCCREATE As Integer = 129
    Public Const WM_NCLBUTTONDOWN As Integer = 161
    Public Const WM_NCLBUTTONUP As Integer = 162
    Public Const WM_NCMOUSEMOVE As Integer = 160
    Public Const WM_NCACTIVATE As Integer = 134
    Public Const WM_NCPAINT As Integer = 133
    Public Const WM_NCHITTEST As Integer = 132
    Public Const WM_NCLBUTTONDBLCLK As Integer = 163
    Public Const WM_INITMENUPOPUP As Int32 = &H117
    Public Const WM_MENUSELECT As Int32 = &H11F
    Public Const WM_APPCOMMAND As Int32 = &H319

    Public Const WM_CONTEXTMENU As Int32 = &H7B

    Public Const VK_LBUTTON As Integer = 1

    Public Const SM_CXSIZE As Integer = 30
    Public Const SM_CYSIZE As Integer = 31
    Declare Function ReleaseDC Lib "user32.dll" ( _
        ByVal hwnd As IntPtr, _
        ByVal hdc As IntPtr) As Int32

    Declare Function GetWindowRect Lib "user32.dll" ( _
        ByVal hwnd As IntPtr, _
        ByRef lpRect As AeroAPIs.RECT) As Int32
    <DllImport("user32")> _
    Public Shared Function GetWindowDC(ByVal hwnd As Integer) As Integer
    End Function
    <DllImport("uxtheme.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> _
    Public Shared Function GetThemeTextExtent(ByVal hTheme As IntPtr, ByVal hDC As IntPtr, ByVal iPartId As Integer, ByVal iStateId As Integer, ByVal pszText As String, ByVal iCharCount As Integer, _
 ByVal dwTextFlags As Integer, ByRef pBoundingRect As RECT, ByVal pExtentRect As RECT) As Integer
    End Function
    Public Enum BITMAPCOMPRESSION
        RGB
        RLE8
        RLE4
        BITFIELDS
        JPEG
        PNG
    End Enum
    Public Const S_OK As Integer = 0
    Public Const SRCPAINT As Integer = &HEE0086
    <DllImport("dwmapi.dll")> _
    Public Shared Function DwmEnableComposition(ByVal bEnable As CompositionEnable) As Integer
    End Function
    Public Enum CompositionEnable As UInteger
        DWM_EC_DISABLECOMPOSITION = 0
        DWM_EC_ENABLECOMPOSITION = 1
    End Enum
    <DllImport("dwmapi.dll", EntryPoint:="#127", PreserveSig:=False)> _
    Public Shared Sub DwmGetColorizationParameters(ByRef parameters As WDM_COLORIZATION_PARAMS)
    End Sub

    <DllImport("dwmapi.dll", EntryPoint:="#131", PreserveSig:=False)> _
    Public Shared Sub DwmSetColorizationParameters(ByRef parameters As WDM_COLORIZATION_PARAMS, ByVal uUnknown As UInteger)
    End Sub

    Public Structure WDM_COLORIZATION_PARAMS
        Public Color1 As UInteger
        Public Color2 As UInteger
        Public Intensity As UInteger
        Public Unknown1 As UInteger
        Public Unknown2 As UInteger
        Public Unknown3 As UInteger
        Public Opaque As UInteger
    End Structure

    ''' <summary>
    ''' Enables the blur effect on the provided window handle.
    ''' </summary>
    ''' <param name="hwnd">The handle to the window for which the blur behind data is applied.</param>
    ''' <param name="pBlurBehind">The pointer to a DWM_BLURBEHIND structure that provides blur behind data.</param>
    ''' <returns>Returns S_OK if successful, or an error value otherwise.</returns>
    <DllImport("DwmApi")> _
    Public Shared Function DwmEnableBlurBehindWindow(ByVal hwnd As IntPtr, ByRef pBlurBehind As DWM_BlurBehind) As Integer
    End Function
    <DllImport("dwmapi.dll", PreserveSig:=False)> _
    Public Shared Function DwmGetColorizationColor(ByVal pcrColorization As Integer, <MarshalAs(UnmanagedType.Bool)> ByVal pfOpaqueBlend As Boolean)
    End Function
    <DllImport("dwmapi.dll", PreserveSig:=False)> _
    Public Shared Function DwmRegisterThumbnail(ByVal dest As IntPtr, ByVal source As IntPtr) As IntPtr
    End Function
    <DllImport("dwmapi.dll", PreserveSig:=False)> _
    Public Shared Function DwmUnregisterThumbnail(ByVal hThumbnail As IntPtr)
    End Function
    <DllImport("dwmapi.dll", PreserveSig:=False)> _
    Public Shared Function DwmUpdateThumbnailProperties(ByVal hThumbnail As IntPtr, ByVal props As Dwm_ThumbnailProperties)
    End Function
    <DllImport("dwmapi.dll", PreserveSig:=False)> _
    Public Shared Function DwmQueryThumbnailSourceSize(ByVal hThumbnail As IntPtr, ByVal size As Size)
    End Function
    <StructLayout(LayoutKind.Sequential)> _
    Public Structure Dwm_ThumbnailProperties
        Public dwFlags As UInt64
        Public rcDestination As RECT
        Public rcSource As RECT
        Public opacity As Byte
        <MarshalAs(UnmanagedType.Bool)> _
        Public fVisible As Boolean
        <MarshalAs(UnmanagedType.Bool)> _
        Public fSourceClientAreaOnly As Boolean
        Public Const DWM_TNP_RECTDESTINATION As UInt32 = &H1
        Public Const DWM_TNP_RECTSOURCE As UInt32 = &H2
        Public Const DWM_TNP_OPACITY As UInt32 = &H4
        Public Const DWM_TNP_VISIBLE As UInt32 = &H8
        Public Const DWM_TNP_SOURCECLIENTAREAONLY As UInt32 = &H10
    End Structure
    ''' <summary>
    ''' Specifies Desktop Window Manager (DWM) blur behind properties.
    ''' </summary>
    <StructLayout(LayoutKind.Sequential)> _
    Structure DWM_BlurBehind
        ''' <summary>
        ''' A bitwise combination of DWM Blur Behind Constants values indiciating which members are set.
        ''' </summary>
        <MarshalAs(UnmanagedType.U4)> _
        Public dwFlags As BlurBehindFlags
        ''' <summary>
        ''' true to register the window handle to DWM blur behind; false to unregister the window handle from DWM blur behind.
        ''' </summary>
        <MarshalAs(UnmanagedType.Bool)> _
        Public fEnable As Boolean
        ''' <summary>
        ''' The region within the client area to apply the blur behind. A NULL value will apply the blur behind the entire client area.
        ''' </summary>
        Public hRgnBlur As IntPtr
        ''' <summary>
        ''' TRUE if the window's colorization should transition to match the maximized windows; otherwise, FALSE.
        ''' </summary>
        <MarshalAs(UnmanagedType.Bool)> _
        Public fTransitionOnMaximized As Boolean
    End Structure
    Public Const DWM_BB_ENABLE As UInt32 = &H1
    Public Const DWM_BB_BLURREGION As UInt32 = &H2
    Public Const DWM_BB_TRANSITIONONMAXIMIZED As UInt32 = &H4
    Public Declare Function CreateDIBSection Lib "gdi32.dll" (ByVal hdc As IntPtr, ByRef pbmi As BITMAPINFO, ByVal iUsage As UInt32, ByVal ppvBits As Integer, ByVal hSection As IntPtr, ByVal dwOffset As UInt32) As IntPtr
    Public Declare Function CreateCompatibleDC Lib "gdi32.dll" (ByVal hDC As IntPtr) As IntPtr
    Public Declare Function SelectObject Lib "gdi32.dll" (ByVal hDC As IntPtr, ByVal hObject As IntPtr) As IntPtr
    Public Declare Function DeleteObject Lib "gdi32.dll" (ByVal hObject As IntPtr) As Boolean
    Public Declare Function DeleteDC Lib "gdi32.dll" (ByVal hdc As IntPtr) As Boolean
    Public Declare Function BitBlt Lib "gdi32.dll" (ByVal hdc As IntPtr, ByVal nXDest As Integer, ByVal nYDest As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hdcSrc As IntPtr, ByVal nXSrc As Integer, ByVal nYSrc As Integer, ByVal dwRop As Int32) As Boolean

    Public Declare Function DwmExtendFrameIntoClientArea Lib "dwmapi.dll" (ByVal hWnd As IntPtr, ByRef margins As MARGINS) As Integer
    Public Declare Sub DwmIsCompositionEnabled Lib "dwmapi.dll" (ByRef IsIt As Boolean)
    <DllImport("UxTheme.dll", ExactSpelling:=True, SetLastError:=True, CharSet:=CharSet.Unicode)> Shared Function DrawThemeTextEx(ByVal hTheme As IntPtr, ByVal hdc As IntPtr, ByVal iPartId As Integer, ByVal iStateId As Integer, ByVal text As String, ByVal iCharCount As Integer, ByVal dwFlags As Integer, ByRef pRect As RECT, ByRef pOptions As S_DTTOPTS) As Integer
    End Function

    Public Const DTT_COMPOSITED As Integer = 8192
    Public Const DTT_GLOWSIZE As Integer = 2048
    Public Const DTT_TEXTCOLOR As Integer = 1
    Public Const SRCCOPY As Integer = &HCC0020
    Public Const WM_SYSCOLORCHANGE As Int32 = &H15

    <StructLayout(LayoutKind.Sequential)> _
    Public Structure MARGINS
        Public Left As Integer
        Public Right As Integer
        Public Top As Integer
        Public Bottom As Integer
        ''' <summary>
        ''' Convert to an array of Rectangles.
        ''' </summary>
        ''' <param name="Parent">Parent control of this MARGINS.</param>
        Public Function ToRectangles(ByVal Parent As Control) As Rectangle()
            If Left > Parent.Width OrElse Top > Parent.Height OrElse Right > Parent.Width OrElse Bottom > Parent.Height OrElse Left < 0 OrElse Right < 0 OrElse Bottom < 0 OrElse Top < 0 Then
                Return New Rectangle(0) {Parent.ClientRectangle}
            End If
            Dim R1 As New Rectangle(Point.Empty, New Size(Parent.Width, Top))
            Dim R2 As New Rectangle(New Point(0, Top), New Size(Left, Parent.Height - Top - Bottom))
            Dim R3 As New Rectangle(New Point(Parent.Width - Right, Top), New Size(Right, Parent.Height - Top - Bottom))
            Dim R4 As New Rectangle(New Point(0, Parent.Height - Bottom), New Size(Parent.Width, Bottom))
            Dim Rects(3) As Rectangle
            Rects(0) = R1
            Rects(1) = R2
            Rects(2) = R3
            Rects(3) = R4
            Return Rects
        End Function
        ''' <summary>
        ''' Gets area that they aren't in this MARGINS.
        ''' </summary>
        Public ReadOnly Property NonArea(ByVal Parent As Control) As Rectangle
            Get
                If Left > Parent.Width OrElse Top > Parent.Height OrElse Right > Parent.Width OrElse Bottom > Parent.Height OrElse Left < 0 OrElse Right < 0 OrElse Bottom < 0 OrElse Top < 0 Then
                    Return New Rectangle(Point.Empty, Size.Empty)
                End If
                Return New Rectangle(Left, Top, Parent.Width - Left - Right, Parent.Height - Top - Bottom)
            End Get
        End Property
    End Structure

    Public Structure RECT
        ''' <summary>
        ''' Create an instance of RECT.
        ''' </summary>
        ''' <param name="Rect">A Rectangle for use its location and size.</param>
        Public Sub New(ByVal Rect As Rectangle)
            Left = Rect.Left
            Top = Rect.Top
            Right = Rect.Right
            Bottom = Rect.Bottom
        End Sub
        Public Function ToRectangle() As Rectangle
            Return Rectangle.FromLTRB(Left, Top, Right, Bottom)
        End Function
        ''' <summary>
        ''' Create an instance of RECT.
        ''' </summary>
        ''' <param name="LeftValue">An integer for set Left property.</param>
        ''' <param name="TopValue">An integer for set Top property.</param>
        ''' <param name="RightValue">An integer for set Right property.</param>
        ''' <param name="BottomValue">An integer for set Bottom property.</param>
        Public Sub New(ByVal LeftValue As Integer, ByVal TopValue As Integer, ByVal RightValue As Integer, ByVal BottomValue As Integer)
            Left = LeftValue
            Top = TopValue
            Right = RightValue
            Bottom = BottomValue
        End Sub

        Public Left As Integer
        Public Top As Integer
        Public Right As Integer
        Public Bottom As Integer
    End Structure

    Public Structure BITMAPINFOHEADER
        Dim biSize As Integer
        Dim biWidth As Integer
        Dim biHeight As Integer
        Dim biPlanes As Short
        Dim biBitCount As Short
        Dim biCompression As Integer
        Dim biSizeImage As Integer
        Dim biXPelsPerMeter As Integer
        Dim biYPelsPerMeter As Integer
        Dim biClrUsed As Integer
        Dim biClrImportant As Integer
    End Structure

    Public Structure RGBQUAD
        Dim rgbBlue As Byte
        Dim rgbGreen As Byte
        Dim rgbRed As Byte
        Dim rgbReserved As Byte
    End Structure

    Public Structure BITMAPINFO
        Dim bmiHeader As BITMAPINFOHEADER
        Dim bmiColors As RGBQUAD
    End Structure

    Public Structure S_DTTOPTS
        Dim dwSize As Integer
        Dim dwFlags As Integer
        Dim crText As Integer
        Dim crBorder As Integer
        Dim crShadow As Integer
        Dim iTextShadowType As Integer
        Dim ptShadowOffset As Point
        Dim iBorderSize As Integer
        Dim iFontPropId As Integer
        Dim iColorPropId As Integer
        Dim iStateId As Integer
        Dim fApplyOverlay As Boolean
        Dim iGlowSize As Integer
        Dim pfnDrawTextCallback As Integer
        Dim lParam As IntPtr
    End Structure

End Class
''' <summary>
''' Indicates which mode of drawing caption bar.
''' </summary>
Public Enum CaptionBarStates
    AutoSet
    Active
End Enum